【发布时间】:2015-06-15 07:35:51
【问题描述】:
角度范围绑定 &(&(&) 是一次性绑定吗? 我看到它被称为单向绑定,但它也是一次性的吗?
假设我有:
<my-custom-directive data-item="item" />
我的指令声明如下:
.directive('myCustomDirective', [
'$log', function ($log) {
return {
restrict: 'E',
templateUrl: '/template.html',
scope: {
dataItem: '&'
}
controller: function ($scope) {
// ....
}
}])
我之所以问绑定是否是一次性的,是因为这似乎是我所观察到的,就是这样。如果父作用域中的item 更新,则指令中的item 不会更新。
我说绑定是一次性的对吗?
为了实现我想要的,指令保留一个副本而不影响父范围的项目——我这样做了:
.directive('myCustomDirective', [
'$log', function ($log) {
return {
restrict: 'E',
templateUrl: '/template.html',
scope: {
dataItemOriginal: '='
},
link: function ($scope) {
$scope.$watch('dataItemOriginal', function () {
$scope.dataItem = window.angular.copy($scope.dataItemOriginal);
});
},
controller: function ($scope) {
//....
}
}])
这是正确的还是有更好的方法?
【问题讨论】:
-
什么是您需要不断更新的副本而不是在需要时复制它的用例?
-
用例是我不知道该怎么做:-)
-
一个简单的函数会不会说
ng-click不能满足您的需求?那么函数里面的$scope.dataItem = window.angular.copy($scope.dataItemOriginal);呢?如果您只需要快照副本,使用$.watch会很昂贵 -
&前缀用于将函数传递到隔离范围。是你想要的吗?此外,在前导data之后使用大写字符命名范围属性也是一个坏主意。这个属性data-item将被解析为item,而不是dataItem
标签: javascript angularjs angularjs-scope angular-directive