指令范围未定义

时间:2014-09-26 00:19:51

标签: angularjs angularjs-scope angularjs-ng-repeat

我遇到了将数据传递给ng-repeat中的angular指令的问题,它总是未定义的。这是我的代码

控制器:

angular.module('module').controller('ModuleController', ['$scope', 'MyService', function($scope, MyService) { 
    $scope.getData = function() {
        $scope.data = MyService.myGetRequest(); // returning array of objects
    };
});

查看:

<div ng-controller="ModuleController" ng-init="getData()" ng-switch="data.length > 0">
   <div ng-repeat="d in data" ng-switch-when="true">
     <my-directive data="d.object"></my-directive>
   </div>
 </div>

指令:

angular.module('module').directive('myDirective', [function() {
    return {
        restrict: 'E',
        template: '<div></div>' // let's ignore the template for now,
        scope: { data: '=' },
        link: function(scope, el, attrs) {
            console.log(scope.data); // always undefined
        }
    };
 }]);

服务:

angular.module('module').factory('MyService', ['$resource', function($resource) {
    return $resource('/data/:id', 
        { id: '@_id' }, 
        { 
            myGetRequest: { method: 'GET', isArray: true } 
        });
}]);

我认为这是因为加载模板时$scope.data仍为空。如果是的话,任何人都知道解决方案是什么?提前致谢。 :)

编辑:顺便说一句,如果我将<my-directive data="data"></my-directive>代替<my-directive data="d.object"></my-directive>scope.data 不再定义,它将显示我的资源对象数组。

EDIT2:此<my-directive data="d"></my-directive>我的指令中scope.data undefined也会{{1}}。

EDIT3:添加服务代码段

1 个答案:

答案 0 :(得分:0)

我认为Shomz发现了这个问题。您应该使用带有异步调用的promise。像这样:

angular.module('module').controller('ModuleController', ['$scope', 'MyService',       
    function($scope, MyService) { 

        $scope.data = [];

        MyService.myGetRequest().$promise.then(function(data) {
            $scope.data = data;
        });
    }

});
相关问题