父指令属性更改时,子指令未更新

时间:2017-03-30 21:26:13

标签: javascript angularjs angularjs-directive

这是对这两个问题的跟进:

  1. Pass argument between parent and child directives
  2. Parent directive controller undefined when passing to child directive
  3. 我有这部分工作;但是,当父指令的ng-disabled值发生更改时,子指令值不会更新。

    请参阅瘦plunkr example

    HTML:

    <div ng-app="myApp">
      <div ng-controller="MyController">
        {{menuStatus}}
        <tmp-menu ng-disabled="menuStatus">
          <tmp-menu-link></tmp-menu-link>
          <tmp-menu-link></tmp-menu-link>
        </tmp-menu>
        <button ng-click="updateStatus()">Update</button>
      </div>
    </div>
    

    的JavaScript(AngularJS):

    angular.module('myApp', [])
    .controller('MyDirectiveController', MyDirectiveController)
    .controller('MyController', function($scope){
      $scope.menuStatus = false;
      $scope.updateStatus = function(){
        $scope.menuStatus = $scope.menuStatus?false:true;
      }
    })
    .directive('tmpMenu', function() {
      return {
        restrict: 'AE',
        replace:true,
        transclude:true,
        scope:{
          disabled: '=?ngDisabled'
        },
        controller: 'MyDirectiveController',
        template: '<div>myDirective Disabled: {{ disabled }}<ng-transclude></ng-transclude></div>',
        link: function(scope, element, attrs) {
    
    
        }
      };
    })
    .directive('tmpMenuLink', function() {
      return {
        restrict: 'AE',
        replace:true,
        transclude:true,
        scope:{
        },
        require:'^^tmpMenu',
        template: '<div>childDirective disabled: {{ disabled }}</div>',
        link: function(scope, element, attrs, MyDirectiveCtrl) {
          console.log(MyDirectiveCtrl);
    
          scope.disabled = MyDirectiveCtrl.isDisabled();
    
        }
      };
    })
    
    function MyDirectiveController($scope) {
      this.isDisabled = function() {
        return $scope.disabled;
      };
    }
    

    如何检测父指令中的更改并将其传递给child指令而不添加角度观察器。

1 个答案:

答案 0 :(得分:1)

解决方案1 ​​

我在这里设置了一个工作的plnkr:https://plnkr.co/edit/fsxMJPAc05imhBqefaRk?p=preview

此行为的原因是tmpMenuLink保留了从MyDirectiveCtrl.isDisabled()返回的值的副本。没有设置观察者,因此解决此问题的唯一方法是手动监视任何更改,然后更新字段。

scope.$watch(function(){
  return MyDirectiveCtrl.isDisabled();
}, function(){
   scope.disabled = MyDirectiveCtrl.isDisabled();
})

解决方案2

没有观察者的替代方案是传递对象的引用而不是基本类型,如:

$scope.menuStatus = {status: false};

新的plnkr:https://plnkr.co/edit/RGEK6TUuE7gkPDS6ygZe?p=preview