从Angular.js中的指令控制器调用工厂

时间:2014-06-30 12:17:54

标签: javascript angularjs angularjs-directive factory

我正在尝试学习Angular.js,我正在使用ng-boiler-plate来管理我的测试应用程序。

然而,我遇到了一个ptoblem并且无法看到它无法正常工作的原因。基本上我正在尝试注入一个工厂,然后从指令控制器调用它。

然而,当我尝试调用它时,我收到错误报告工厂名称(在本例中为dashboardFac)未定义。

我将在下面包含该指令和工厂:

指令:

angular.module( 'locationSelector', [
'ngBoilerplate.locationFactory'
] )

.directive( 'locationSelector', function() {
return {
    restrict: 'A',
    //template: '<h3>asdfasdfasd</h3>',
    templateUrl : 'components/locationSelector/locationSelector.tpl.html',
    link: function( scope, element, attrs ) {

        console.log("link working ");

        var $input = angular.element( document.querySelector( '#location' ) );

        $input.bind('focus', function() {
            console.log("stay focused son");
        });

    },
    controller: function($scope, dashboardFac, $element){
        $scope.locyTexy = "";
        $scope.api = dashboardFac;
        console.log($scope.api);
        $scope.change = function() {
            console.log("asdfasd");
            dashboardFac.assets.getLocations().then(function(result){  

            });
        };

    }
    };
})

;

厂:

angular.module( 'ngBoilerplate.locationFactory', [

  ]).factory('dashboardFac', function($http, $q){
    this.assets = {
      getLocations: function(args) {
      var deferred = $q.defer();
      var parmUrl = "will be some url eventually";
      $http.jsonp({
          method: 'GET',
          url: parmUrl
      }).
      success(function(data, status) {
         deferred.resolve(data);
       }).
       error(function(data, status) {
         deferred.reject(data);
       });

      return deferred.promise;
    }
  };
}); 

任何帮助都会受到很大的影响,我有一种感觉,我错过了一些基本的东西,但希望有人可以帮我指出正确的方向。

提前致谢。

2 个答案:

答案 0 :(得分:3)

您必须将dashboardFac工厂注入指令:

.directive( 'locationSelector', function(dashboardFac) {
[…]
})

答案 1 :(得分:1)

正如Krzysztof Safjanowski所指出的那样,您必须先将factory注入directive

   .directive( 'locationSelector', function(dashboardFac) {
      […]
    })

然后你的工厂必须像其他工厂一样返回一个Object:

angular.module( 'ngBoilerplate.locationFactory', [])
  .factory('dashboardFac', function($http, $q){
    return {
      assets: {
        getLocations: function (args) {
          var deferred = $q.defer();
          var parmUrl = "will be some url eventually";
          $http.jsonp({
            method: 'GET',
            url: parmUrl
          }).
            success(function (data, status) {
              deferred.resolve(data);
            }).
            error(function (data, status) {
              deferred.reject(data);
            });

          return deferred.promise;
        }
      }
    }
});