如何在指令中进行自己的ng-change和ng-model?

时间:2019-02-08 12:28:47

标签: angularjs angularjs-directive

我正在尝试使用自己的模型和change属性(作为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

1 个答案:

答案 0 :(得分:0)

您应该使用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