我正在做一个项目,我有一个 Controller 和两个指令,我需要在它们之间共享范围,我创建了 plnkr here.
代码结构如下:
主 Controller
--可绘制指令
----绘制矩形指令
在 Main ctrl
中,有一个对象 rois
在范围内,我要 Drawable
和 Draw-rectangle
指令。单击 drawable 时,它会更新到主 Controller 的范围,但是当我单击 draw-rectangle 指令时,它不会更新范围。
我想使用双向数据绑定(bind)同步所有 (3)
范围。
这在概念上似乎是正确的,但为什么它不更新 Draw-rectangle
指令的范围?
提前致谢!
最佳答案
当您单击“draw-rectangle”时,您也单击了“drawable”,因为“draw-rectangle”在“drawable”中。您必须使用 event.preventDefault() 停止从“draw-rectangle”到“drawable”的传播;如下:
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.rois = [{
name: 'Jack',
city: 'pune'
}, {
name: 'Tony',
city: 'Mumbai'
}];
$scope.test = "Test";
});
app.directive('drawable', [
function() {
return {
restrict: "EA",
link: function(scope, element, attrs) {
element.on('click', function(event) {
event.preventDefault();
scope.rois = [{
name: 'Stark',
city: 'pune'
}, {
name: 'Inc',
city: 'Mumbai'
}];
scope.$apply();
console.log(scope.rois);
});
}
};
}
]);
app.directive('drawRectangle', [
function() {
return {
restrict: "EA",
link: function(scope, element, attrs) {
element.on('click', function(event) {
event.stopPropagation(); // STOP PROPAGATION
event.preventDefault();
scope.rois = [{
name: 'Meuk',
city: 'pune'
}, {
name: 'Tony',
city: 'Mumbai'
}];
scope.$apply();
console.log(scope.rois);
});
}
};
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller='MainCtrl' style='width: 400px;height: 400px;border: 1px solid red;'>
<div drawable rois="rois" style='width: 300px;height: 300px;border: 1px solid red;'>
<div draw-rectangle rois="rois" style='width: 200px;height: 200px;border: 1px solid red;'>
<button type="button" style='margin: 20px; border: 1px solid red;'>Click me!</button>
</div>
</div>
<br>
<br>{{rois | json}}
</div>
关于javascript - 两个指令之间的 Angular 指令范围共享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33124353/