[英]Angularjs get scope attribute without using isolated scope in custom directive
[英]Angularjs: How to update parent scope in directive without using isolated scope when the attribute is passed in within ngRepeat
我有一个简单的angularjs指令,该指令使用JQuery将模板转换为可拖动对话框
var myApp = angular.module("myApp", []);
myApp.controller('myCtrl', function ($scope) {
$scope.tasks = [{
name: 'learn angular',
show: false
}, {
name: 'build an angular app',
show: false
}];
$scope.showBox = function (taskname) {
for (var i = 0; i < $scope.tasks.length; i++) {
if ($scope.tasks[i].name === taskname) {
$scope.tasks[i].show = !$scope.tasks[i].show;
}
}
}
});
myApp.directive("draggableDialog", function () {
return {
template: 'task: {{task.name}}',
link: function (scope, element, attrs) {
element.dialog({
title : "My Dialog",
autoOpen: false
});
element.bind("dialogclose", function () {
if (!scope.$$phase) {
scope.$apply(function () {
scope[attrs.draggableDialog] = false; //here is the problem
});
}
});
scope.$watch(attrs.draggableDialog, function (v) {
if (v) {
element.dialog("open");
} else {
element.dialog("close");
}
});
}
}
});
我在ngRepeat中使用此指令
<div>
<h2>Draggable Dialog</h2>
<div ng-controller="myCtrl">
<ul class="unstyled">
<li ng-repeat="task in tasks">
<button ng-click="showBox(task.name)">show {{task.name}}</button>{{task.show}}
<div draggable-dialog="task.show">test</div>
</li>
</ul>
</div>
</div>
请参阅此提琴: http : //jsfiddle.net/tianhai/BEtPk/#base
当用户手动关闭对话框时,我可以检测到该事件,并且要将myCtrl中的$ scope.task [i] .show设置为false。 我该怎么做? 我无法使用隔离作用域双向绑定,因为我正在使用此指令以及另一个也包含$ scope.task的指令。
您已将attrs.draggableDialog
设置为“ task.show”,因此当您进行scope[attrs.draggableDialog] = false
,最终会得到一个附加到范围的元素,您可以使用scope['task.show']
访问该元素,该元素不同于scope['task']['show']
或scope.task.show
要将父变量设置为false,通常需要评估一个包含赋值的字符串。 对于您来说,它看起来像这样:
scope.$eval(attrs.draggableDialog + ' = false;');
希望这有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.