I wrote a directive myself, as follows:
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>\
...\'
};
}
Then the problem comes. It is expected that the two sources will return two different sets of data, but the actual situation is that the data displayed in the two lists is the same, and it is the data returned by the second function listTwo(), that is, if I swap the positions of listOne() and listTwo(), and the data returned is the data of listOne().
Could it be
var data = new DataList(scope.source);
...
scope.dataset = data.list;
When using new for the second time, did you replace the data from the first time?
But doesn’t scope:{source: '&'} generate its own scope for the directive?
I want to learn directive well, thank you in advance
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