简体   繁体   English

在自定义指令的控制器中更新$ scope时,Angular.js双向绑定不起作用?

[英]Angular.js two-way binding do not work when update the $scope in the controller of custom directive?

I met this when I was writing a group of directives which can contact with each other. 我在编写一组可以相互联系的指令时遇到了这个问题。

Here is the CodePen url: http://codepen.io/jennieji/pen/mDGuw 这是CodePen网址: http ://codepen.io/jennieji/pen/mDGuw

Here is the JS code: 这是JS代码:

angular.module('app', [])
.directive('testDirective', function() {
  return {
    controller: function($scope){
      $scope.now = 0;

      this.update = function() {
        $scope.now++;
      };
    },
    link: function(scope) {
      scope.$watch(function(){
        return scope.now;
      }, function(newVal, oldVal) {
        element.append('<p>[LOG] $watch now:' + newVal + '</p>');
      }, true);
      scope.$watch('now', function(newVal, oldVal) {
        element.append('<p>[LOG] $watch now:' + newVal + '</p>');
      });
    }
  };
})
.directive('testUpdate', function() {
  return {
    require: '^testDirective',
    link: function(scope, element, attr, ctrl) {
      element.on('click', function(){
        ctrl.update();
        element.after('<p>[LOG] click now:' + scope.now + '</p>');
      });
    }
  }
});

Here is the HTML: 这是HTML:

<div ng-app="app">
  <div test-directive>
    <p>{{ now }}</p>
    <button test-update>Update now</button>
  </div>
<div>

Since you are listening for the DOM click event: 由于您正在监听DOM click事件:

element.on('click', function(){

Your scope changes will not take effect unless you $apply them: 除非您$apply否则您的范围更改将不会生效:

link: function(scope, element, attr, ctrl) {
      element.on('click', function(){

        scope.$apply(function() {
          ctrl.update();
        });
        ctrl.update();
        element.after('<p>[LOG] click now:' + scope.now + '</p>');

      });
    }

$apply kicks off an Angular $digest loop and does the dirty check for the two-way bind. $apply启动Angular $digest循环,并进行双向绑定的脏检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM