Javascript Angularjs 1.2.6:手表指令';s父作用域集合
我正在生成自定义树指令:Javascript Angularjs 1.2.6:手表指令';s父作用域集合,javascript,angularjs,angularjs-directive,Javascript,Angularjs,Angularjs Directive,我正在生成自定义树指令: <ul tree="treeOptions"> <li>{{ item.code + ' - ' + item.name }}</li> </ul> (function (angular) { 'use strict'; angular.module('tree', []). directive('tree', ['$compile', '$document', function
<ul tree="treeOptions">
<li>{{ item.code + ' - ' + item.name }}</li>
</ul>
(function (angular) {
'use strict';
angular.module('tree', []).
directive('tree', ['$compile', '$document', function ($compile,
$document) {
return {
restrict: 'A',
scope: { treeOptions: '=tree' }, //Isolated scope
compile: function (elem, attrs) {
//...
return function (scope, elem, attrs) {
//...
scope.$parent.$watchCollection(scope.treeOptions.data,
function (newItems, oldItems) {
var addedItems = _.difference(newItems, oldItems);
var removedItems = _.difference(oldItems, newItems);
//but newItems and oldItems always the same
//...
}
);
}
};
}
};
} ]);
})(angular);
在指令中:
<ul tree="treeOptions">
<li>{{ item.code + ' - ' + item.name }}</li>
</ul>
(function (angular) {
'use strict';
angular.module('tree', []).
directive('tree', ['$compile', '$document', function ($compile,
$document) {
return {
restrict: 'A',
scope: { treeOptions: '=tree' }, //Isolated scope
compile: function (elem, attrs) {
//...
return function (scope, elem, attrs) {
//...
scope.$parent.$watchCollection(scope.treeOptions.data,
function (newItems, oldItems) {
var addedItems = _.difference(newItems, oldItems);
var removedItems = _.difference(oldItems, newItems);
//but newItems and oldItems always the same
//...
}
);
}
};
}
};
} ]);
})(angular);
我正在使用lodash(41;查找新项目和旧项目之间的差异。
问题是newItems和oldItems总是相同的,即使在将新项推送到父范围的myItems数组之后也是如此。我错过了什么 所以,这绝对是角度框架中的一个问题。我相信他们迟早会着手解决这个问题,但与此同时,如果您需要让代码正常工作,我就能够编写出一个非常有效的示例。核心是不使用默认的旧/新元素:
var oldWorkingItems = scope.$parent[attrs.testDirective].slice(0);
scope.$parent.$watchCollection(attrs.testDirective,
function (newItems, oldItems) {
console.log('NEW Items:' + newItems);
console.log('Old Items:' + oldWorkingItems);
有关完整示例以及我对错误的再现,请参见以下示例:。顺便说一下,之所以多次调用它,是因为它位于ng repeat中,但这是我强制使用“$parent”的方式。不管怎样,希望这对你有所帮助
编辑-指令在ng repeat中运行了多少次,这让我非常恼火,因此我编写了另一个plunker(),它使用单个ng repeat:
<div ng-repeat="element in [1]">
<div test-directive="testCollection"></div>
</div>
这只调用了两次指令(为什么调用了两次,我还不确定)。正如Gruff Bunny在评论中指出的,这是AngularJS在当前版本(1.2.13)之前的一个公开问题。现在的解决方法是使用
$watch(,true)
或按照drew的建议执行。您是否尝试过自己循环并查看每个变量中实际包含的内容?是的,推送后,newItems和oldItems都包含推送项。可能该函数被多次调用?请参阅