在手表中访问子范围

时间:2016-09-08 10:03:15

标签: angularjs

在这个plunk中,我有两个嵌套的指令,每个都有一个复选框。我的目标是在用户单击子复选框时更改父复选框。我需要使用watch(没有消息),但我无法访问子范围。有什么想法吗?

的Javascript

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


angular.module('app')
    .directive('directive1', function() 

    var directive = {};

    directive.restrict = 'E';

    directive.scope = true;

    directive.template = '<input type="checkbox" ng-model="cb1"> Top directive <br/><directive2></directive2> ';

    directive.link = function(scope, element, attrs) {

      scope.$watch(function () {'cb2' }, 
              function (newValue, oldValue) {
                  scope.cb1 = newValue;
       });


    };

    return directive;

});


angular.module('app')
    .directive('directive2', function() {

    var directive = {};

    directive.restrict = 'E';

    directive.scope = true;

    directive.template = '<input type="checkbox" ng-model="cb2">  Bottom directive ';

    directive.link = function(scope, element, attrs) {
    };

        return directive;

});

2 个答案:

答案 0 :(得分:1)

您可以在父级中设置一个功能,以便选中复选框。

在子指令require中父母并调用其功能。

.uniq

http://plnkr.co/edit/zM3Gip5DLbmtPOuxrhif?p=preview

我冒昧地重构你的代码。

答案 1 :(得分:1)

要使原型继承正常工作,ng-model指令需要具有带“点”的值。

<input type="checkbox" ng-model="d1.cb2">

然后父指令需要创建d1对象并观察d1.cb2

angular.module('app')
.directive('directive1', function() {
    var directive = {};
    directive.restrict = 'E';
    directive.scope = true;
    directive.template = '<input type="checkbox" ng-model="cb1"> Top directive <br/><directive2></directive2> ';

    directive.link = function(scope, element, attrs) {
      scope.d1 = {};
      scope.$watch('d1.cb2', 
                    function (newValue, oldValue) {
                       scope.cb1 = newValue;  
                    }
      );
    };

    return directive;

});
  

范围继承通常很简单,你甚至不需要知道它正在发生......直到你尝试双向数据绑定(即表单元素,ng-model) 到原始(例如,数字,字符串,布尔值)在子范围内从父范围定义。它不像大多数人期望的那样工作。会发生什么是子范围获取其自己的属性,该属性隐藏/隐藏同名的父属性。这不是AngularJS正在做的事情 - 这就是JavaScript原型继承的工作原理。

有关原型继承的更多信息,请参阅AngularJS Wiki -- The Nuances of Scope Prototypal Inheritance

DEMO on PLNKR

相关问题