如何将ng-model / $scope与Angular Factory和Controller一起使用

How to use ng-model / $scope with Angular Factory and Controller

本文关键字:Factory Controller 一起 Angular ng-model scope      更新时间:2023-09-26
// SERVICES
app.factory('searchFactory', ['$http', function($http) {
    return $http.post("/api", { tag: "food" });
}]);
// CONTROLLERS
app.controller('MainController', ['$scope', 'searchFactory', function ($scope, searchFactory) {
    $scope.submit = function () {
      searchFactory.then(function(response) {
        $scope.recipeData = JSON.parse(response.data);
      });
    };
// HTML
    <form ng-submit="submit()">
      <div class="form-group">
        <input type="text" ng-model="recipeTag" class="form-control" />
        <input type="submit" class="btn btn-primary" value="Find Recipes" />
      </div>
    </form>

有谁知道我如何使用ng-model的$scope.recipeTag来代替工厂中的"食物"?我需要能够将表单输入作为参数传递到工厂中。

您需要

创建一个函数,该功能需要工厂中的参数。

例:

            var factory= {
                post: function(customTag) {
                    return $http.post("/api", { tag: customTag });
                }
            };
            return factory;