首页 > angularjs在directive中使用函数的问题

angularjs在directive中使用函数的问题

我自己写了一个directive,如下:

html

<myDirective source="listOne()"</myDirective>
<myDirective source="listTwo()"</myDirective>

controller

...
$scope.listOne = function(){
    //返回一个promise
};
$scope.listTwo = function(){
    //返回另一个promise
};
...

directive

angular.module('myApp')
    .directive('myDirective', function() {
        function DataList(sourceFn) {
            var debounceId;
            self.list = [];
            self.load = function(){
                $timeout.cancel(debounceId);
                debounceId = $timeout(function() {
                    var promise = sourceFn();
                    promise.then(function(data) {
                        self.list = data;
                    });
                },0,false);
            };
            return self;
        }

        return {
            restrict: 'E',
            replace: true,
            scope: {
                source: '&'
            },
            link: function(scope, element, attr) {
                ...
                var data = new DataList(scope.source);
                ...
                scope.dataset = data.list;
                ...
            },
            template: '\
            ...\
            <li ng-repeat="d in dataset">{{d}}</li>\
            ...\'
        };
    }

那么问题来了,预期的是两个source会返回不同的两组数据,但是实际情况是两个列表显示的数据相同,而且是第二个函数listTwo()返回的数据,也就是如果我把listOne()和listTwo(),调换位置,那么返回的就是listOne()的数据。
难道是在

var data = new DataList(scope.source);
...
scope.dataset = data.list;

第二次new的时候把第一次的数据替换了?
但是scope:{source: '&'}不是会为directive生成一个自己的scope吗?
想好好学习下directive,先谢过各位


是你的DataList的问题,你返回的是self引用,看样子应该是window了,所以对应的list是一个全局变量,这样不管你赋值多少次,只有最后一次生效

【热门文章】
【热门文章】