如何在Angular Factory和Controller

时间:2015-11-16 00:32:07

标签: javascript angularjs http scope factory

// 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替换&#34; food&#34;在工厂?我需要能够将表​​单输入作为参数传递给工厂。

1 个答案:

答案 0 :(得分:1)

您需要创建一个需要工厂参数的功能。

示例:

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