[英]Angular update scope with individual values for $watch inside directive
Let's say I have two draggable elements 假设我有两个可拖动元素
<div draggable enabled="false"></div>
<div draggable enabled="false"></div>
To enable/disable the elements I use the following directive: 要启用/禁用元素,我使用以下指令:
App.directive('draggable', function() {
return {
restrict:'A',
link: function(scope, element, attrs) {
element.draggable();
scope.$watch('enabled', function (val) {
element.draggable(val === true ? 'enable' : 'disable');
});
}
};});
I have setup a $watch looking enabled to be true/false. 我已经设置了一个$ watch,看起来是true / false。 Now I would like to use my controller to change the 'enabled' property.
现在,我想使用我的控制器来更改“ enabled”属性。
App.controller('TypeAheadController',function($scope){
//some code
$scope.enabled = true;
});
However, when I use this, ALL the draggable elements are referenced. 但是,当我使用它时,将引用所有可拖动元素。 So they all get enabled or disabled.
因此它们都被启用或禁用。 Which I think is strange, as I would expect the $watch to look for the enabled value inside the scope for each draggable element.
我认为这很奇怪,因为我希望$ watch在每个可拖动元素的范围内查找启用的值。 My goal is to enable/disable the draggable element individually.
我的目标是分别启用/禁用可拖动元素。 So I need a way to set/reference the enabled property for each draggable element in the controller.
因此,我需要一种方法来设置/引用控制器中每个可拖动元素的enabled属性。
You can change the directive to have it's own scope: 您可以更改指令以使其具有自己的作用域:
App.directive('draggable', function () {
return {
restrict: 'A',
scope: {
enabled: '='
},
link: function (scope, element, attrs) {
element.draggable();
scope.$watch('enabled', function (val) {
element.draggable(val === true ? 'enable' : 'disable');
});
}
};
});
To have your controller control each individual directive you would need to have a corresponding configuration for each directive: 要让控制器控制每个单独的指令,您需要为每个指令具有相应的配置:
App.controller('TypeAheadController', function ($scope) {
$scope.draggableItems = [{enabled:true},{enabled: true}];
});
and in your HTML: 并在您的HTML中:
<div ng-repeat="draggable in draggableItems" draggable enabled="draggable.enabled"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.