angular.js - angularjs在directive中使用函数的问题
巴扎黑
巴扎黑 2017-05-15 16:50:57
0
1
488

我自己写了一个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,先谢过各位

巴扎黑
巴扎黑

reply all(1)
Ty80

It’s a problem with your DataList. What you return is a self reference, which seems to be window, so the corresponding list is a global variable, so no matter how many times you assign a value, only the last one takes effect

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template