【问题标题】:Call the function in parent scope within a directive does not update parent scope在指令内调用父范围内的函数不会更新父范围
【发布时间】:2014-09-23 08:56:53
【问题描述】:

我尝试在指令链接函数中调用父范围内的函数来更新父范围属性之一。

var app = angular.module('myApp', []);

app.controller('MyCtrl', function($scope) {
    var users = [{
        name: 'Andy',
        age: 9
    },{
        name: 'Tom',
        age: 10
    },{
        name: 'Jerry',
        age: 11
    },{
        name: 'Harry',
        age: 12
    }];

    $scope.users = users;
    $scope.currentUser = users[0];
    $scope.updateCurrentUser = function(index) {
        $scope.currentUser = users[index];
    };
});

app.directive('myDirective', function() {
    return {
        template: '<div><button ng-repeat="user in users">{{ user.name }}</button></div>',
        restrict: 'EA',
        link: function(scope, element, attrs) {
            element.on('click', 'button', function() {
                scope.updateCurrentUser($(this).index());
            });
        }
    };
});

source code

假设我点击任意按钮,currentUser 应该会显示更新对应的用户数据。但是,看起来它不起作用。我想知道为什么以及如何解决这个问题?

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    因为 click 事件是在 Angular 不知情的情况下处理的,所以您需要 $apply 您的更改:

    element.on('click', 'button', function() {   
        scope.updateCurrentUser($(this).index());
        scope.$apply();
    });
    

    $apply 运行和 Angular $digest$digest 将负责父级中的双向绑定。

    【讨论】:

    • 当她可以使用 ng-click 指令来完成时,为什么 OP 应该使用 $apply 和 jquery 事件?
    • 根据上下文,有些事情不能通过向模板添加属性来轻松完成。所以,这是对这个问题的一个很好的回答。 ng-click 基本上是在下面做这个。
    • 很公平,但在这种情况下,已经有一个指令......我的意思是,每当我必须在 angularjs 中集成一个外部插件时,我都会为此创建一个指令,在这个如果没有必要,因为已经创建了一个处理点击事件的指令。
    【解决方案2】:

    你不需要使用jQuery 事件,你可以使用ngClick 指令,你的代码会更加简洁和对angularjs 友好:

    改变你的指令,让它变成这样:

    app.directive('myDirective', function() {
      return {
        template: '<div><button ng-click="updateCurrentUser($index)" ng-repeat="user in users">{{ user.name }}</button></div>',
        restrict: 'EA'
      };
    });
    

    Working example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-06
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多