在模型更新之前调用angular指令内的回调

时间:2016-02-22 12:10:56

标签: javascript angularjs angularjs-directive

我已经将模型和回调映射到父作用域的指令。 问题是父模型在回调发生后更新,但在代码中它被分配到BEFORE。

DEMO:PLUNKER (单击两次或更多次,您将看到该模型在单击回调后正在更新)

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

app.controller('MainCtrl', function($scope) {
  $scope.test = true;
  $scope.test2 = true;
  $scope.triggerCallback = function()
  {
      $scope.test2 = $scope.test;//it always see previous value here
  };
}).directive('testdirective', [function () {
    return {
        restrict: 'A',
        template: '<span ng-click="clicked()">from directive: {{checked}}</span>',
        replace: true,
        scope: {
            bindModel: '=ngModel',
            clickCallback: '&onClick'
        },
        link: function (scope, element) {
            scope.checked = scope.bindModel;

            scope.clicked = function () {
                scope.checked = !scope.checked; 
                scope.bindModel = scope.checked;//MODEL UPDATE


              //callback is called AFTER model updating, but model is updated after that
                if (scope.clickCallback != undefined)
                    scope.clickCallback();
            };
        }
    }
}]);

HTML:

<body ng-controller="MainCtrl">
    <a href="">
      <div testdirective ng-model="test" on-click="triggerCallback()"></div>
    </a>
    <br/>
    <span>{{test2}}</span>
  </body>

我知道我可以解决方法并在回调函数中传递新值,但在某些情况下它还不够 - 所以我想直接解决它

1 个答案:

答案 0 :(得分:1)

这是一个常见的双向数据绑定错误。

$ scope。$ apply是一个解决方案,但也许你得到$ digest已经运行异常。所以你需要使用$ timeout,它将在当前的摘要周期结束后执行。

$timeout(function(){
  if (scope.clickCallback != undefined) 
    scope.clickCallback(); 
  };
});

有关角度生命周期的更多信息:http://onehungrymind.com/notes-on-angularjs-scope-life-cycle/