【问题标题】:Angularjs: How to update parent scope in directive without using isolated scope when the attribute is passed in within ngRepeatAngularjs:如何在ngRepeat中传入属性时在不使用隔离范围的情况下更新指令中的父范围
【发布时间】:2014-02-26 06:21:52
【问题描述】:

我有一个简单的 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。

【问题讨论】:

  • 为什么不想使用隔离作用域?它会解决你的问题
  • 嗨,Alex,我无法使用隔离作用域。这是因为我将此指令与另一个元素指令一起使用,该指令必须采用相同的 $scope.task 作为其隔离范围变量。 angular 抱怨 2 个指令不能接受同一个作用域变量

标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat


【解决方案1】:

您已将attrs.draggableDialog 设置为“task.show”,因此当您这样做时 scope[attrs.draggableDialog] = false 你最终会得到一个附加到范围的元素,你可以使用 scope['task.show'] 访问它,这与 scope['task']['show']scope.task.show 不同

要将父变量一般设置为 false,您需要评估包含赋值的字符串。对你来说,它看起来像这样:

scope.$eval(attrs.draggableDialog + ' = false;');

希望这有帮助

【讨论】:

  • 嗨,hassassin,我明白这个问题。但是,我希望这个指令可以是一个通用指令,可以在任何地方使用,无论是它本身,在 ngRepeat 中,还是在我的实际实现中,在第二级嵌套的 ngRepeat 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多