我正在开发一个项目,我有一个控制器和两个指令,我需要在它们之间共享范围,我创建了plnkr here.
代码结构如下:
Main Controller
--Drawable Directive
----Draw-rectangle Directive
在Main ctrl
中,我在rois
和Drawable
指令范围内有一个对象Draw-rectangle
。并且在点击drawable时它会更新到Main控制器的范围,但是当我点击draw-rectangle指令时它没有更新范围。
我希望使用双向数据绑定同步所有(3)
范围。
从概念上看,这似乎是正确的,但为什么不从Draw-rectangle
指令更新范围?
提前致谢!
答案 0 :(得分:1)
你需要停止冒泡事件,因为当rect指令点击时,drawable也会触发点击!使用event.stopPropagation()
var app = angular.module('myApp');
app.directive('drawable', ['$document',
function($document) {
return {
restrict: "EA",
scope: {
rois: '='
},
link: function(scope, element, attrs) {
console.log(scope.rois);
element.on('click', function(event) {
event.stopPropagation();
scope.rois = [{
name: 'Stark',
city: 'pune'
}, {
name: 'Inc',
city: 'Mumbai'
}];
scope.$apply();
console.log(scope.rois);
});
}
};
}
]);
app.directive('drawRectangle', ['$document',
function($document) {
return {
restrict: "EA",
scope: {
rois: '='
},
link: function(scope, element, attrs) {
element.on('click', function(event) {
event.stopPropagation();
scope.rois = [{
name: 'Meuk',
city: 'pune'
}, {
name: 'Tony',
city: 'Mumbai'
}];
scope.$apply();
console.log(scope.rois);
});
}
};
}
]);

答案 1 :(得分:1)
点击"绘制矩形"你也点击了#34; drawable"因为"绘制矩形"在里面" drawable"。你必须停止传播" draw-rectangle" to" drawable"使用event.preventDefault();如下:
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>
&#13;
答案 2 :(得分:0)
您正在为两个指令使用隔离范围。隔离范围将创建子范围。因此,您无法从指令的链接功能中访问“rois”。 删除隔离范围后尝试
scope: {
rois: '='
},