【问题标题】:AngularJS : Directive updating parent scope inside of ng-repeatAngularJS:在 ng-repeat 内更新父范围的指令
【发布时间】:2015-11-06 20:27:57
【问题描述】:

我在 ng-repeat 图像中有一个自定义的可拖动指令。我想在拖动后存储每个图像的 x,y 偏移量。因此,我需要指令来更新图像上的字段。

return {
    restrict: 'A',
    scope: false,
    link: function(scope, element, attrs){
        element.draggable({
            containment: "parent",
            cursor: "crosshair",
            stop: function(ev, ui) {
              scope.left=ui.helper[0].style.left;
              scope.top=ui.helper[0].style.top;
          }
       });
     }
  };

  <div ng-repeat="image in images" 
       draggable
       ng-style="{left:image.left,
                 top:image.top}">... image stuff here ...</div>

不幸的是,这不起作用,因为当 ng-repeat 为每个图像项创建子范围时,它

创建一个新作用域,其原型继承自父作用域 范围,但它还将项目的值分配给 子范围。 (新属性的名称是循环变量的名称。) (https://github.com/angular/angular.js/wiki/Understanding-Scopes#ng-repeat)

通过更改引用以使用循环变量名,我可以让指令按我的意愿工作:

scope.image.left=ui.helper[0].style.left;
scope.image.top=ui.helper[0].style.top;

但我不想将循环变量名称硬编码到指令中。

将循环变量名称传递给指令的最佳方法是什么,或者理想情况下,将项目值的引用直接传递给指令的最佳方法是什么?

【问题讨论】:

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


    【解决方案1】:

    在这种情况下,使用隔离作用域并使用双向绑定将当前图像对象传递给指令是很方便的。

    所以 HTML 可以是这样的:

    <div ng-repeat="image in images" draggable="image" ng-style="{left:image.left, top:image.top}">
        <!-- ... image stuff here ... -->
    </div>
    

    然后是指令:

    .directive('draggable', function () {
        return {
            scope: {image: '=draggable'},
            link: function (scope, element, attrs) {
                element.draggable({
                    containment: "parent",
                    cursor: "crosshair",
                    stop: function (ev, ui) {
                        scope.image.left = ui.helper[0].style.left;
                        scope.image.top = ui.helper[0].style.top;
                    }
                });
            }
        };
    });
    

    这样您不再对变量名进行硬编码,并使指令更可重用。例如,您可以将 HTML 更改为 ng-repeat="img in images" draggable="img",但指令代码将保持不变。

    【讨论】:

    • 这对我有用,没有digest=draggable 正是我想要的,谢谢!
    • @PankajParkar 这里不需要摘要,因为你直接修改对象属性,所以利用直接对象引用。
    • @dfsq 我在想stop 是事件,我们正在从事件中操纵范围,那么 Angular 怎么知道我应该触发摘要?
    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 2013-03-15
    • 1970-01-01
    • 2015-07-01
    • 2016-02-06
    • 1970-01-01
    • 2018-08-12
    相关资源
    最近更新 更多