如何在指令中制作我自己的 ng-change 和 ng-model?

How to make my own ng-change and ng-model in a directive?

我正在尝试使用自己的模型和更改属性(作为 ng-model 和 ng-change 的覆盖)来实现一个指令。它显然工作正常但是当执行父作用域的函数并且在其中修改作用域的一些变量时,它被延迟,如果不是在上一步中执行的,则看不到当前变化。

我已经尝试添加超时、$apply、$digest ...但我无法使其同步

angular.module('plunker', []);

//Parent controller
function MainCtrl($scope) {

  $scope.directiveValue = true;

  $scope.textValue = "init";

  $scope.myFunction = 

  function(){

    if($scope.directiveValue === true){

      $scope.textValue = "AAAA";

    }else{

      $scope.textValue = "BBBB";

    }
  }
}

//Directive
angular.module('plunker').directive('myDirective', function(){

  return {

    restrict: 'E',

    replace: true,

    scope: {

      myModel: '=model',
      myChange: '&change'

    },   

    template: '<span>Check<input ng-model="myModel" ng-change="myChange()" 
       type="checkbox"/></span>', 
   controller: function($scope) {

   },
   link: function(scope, elem, attr) {

     var myChangeAux = scope.myChange;

     scope.myChange = function () {
       setTimeout(function() {
         myChangeAux();
       }, 0);
     };

   }
});

// Html
<body ng-controller="MainCtrl">

  <my-directive model="directiveValue" change="myFunction()"></my-directive>
  <div>Valor model: {{directiveValue}}</div>
  <div>Valor texto: {{textValue}}</div>
</body>

正确的结果是 "myFunction" 函数正确运行

示例:https://plnkr.co/edit/q3IqRCIhwLChlGrkDxyO?p=preview

您应该使用 AngularJS' $timeout,它是浏览器默认值 setTimeout 的包装器,并在内部调用 setTimeout 以及 $digest,所有在正确的时间执行。

您的指令代码应更改为:

angular.module('plunker').directive('myDirective', function($timeout){

  return {
    restrict: 'E',
    replace: true,
    scope: {
      myModel: '=model',
      myChange: '&change'
    },   
    template: '<span>Check<input ng-model="myModel" ng-change="myChange()" type="checkbox"/></span>', 
    controller: function($scope) {
    },
    link: function(scope, elem, attr) {
      var myChangeAux = scope.myChange;

      scope.myChange = function () {
        $timeout(myChangeAux, 0);
      };
    }
  };
});

Docs for AngularJS $timeout