当使用控制器作为语法时,如何从父指令继承属性?

时间:2015-04-07 19:56:37

标签: javascript angularjs angularjs-directive angularjs-scope

我想在Angular指令中使用Controller As语法有两个原因。它更简单的JS,并且不依赖于在Angular 2.0中不可用的$ scope服务。

它适用于单个指令,但我无法弄清楚如何在子指令中从父指令的控制器中打印属性。

function parentCtrl () {
  this.greeting = { hello: 'world' };
}

function childCtrl () {}


angular.module('app', [])
  .controller('parentCtrl', parentCtrl)
  .controller('childCtrl', childCtrl)
  .directive('myParent', function () {
    return {
      scope: {},
      bindToController: true,
      controller: 'parentCtrl',
      controllerAs: 'parent',
      template: '<my-child></my-child>'
    }
  })
  .directive('myChild', function () {
    return {
      scope: {
        greeting: '='
      },
      bindToController: true,
      controller: 'childCtrl',
      controllerAs: 'child',
      template: '<p>{{ greeting.hello }}</p>'
    }
  });

2 个答案:

答案 0 :(得分:1)

您必须require父控制器,使用link函数将父级注入子级。 myChild指令将成为:

.directive('myChild', function () {
    return {
        scope: {
            // greeting: '=' // NO NEED FOR THIS; USED FROM PARENT
        },
        bindToController: true, // UNNECESSARY HERE, THERE ARE NO SCOPE PROPS
        controller: 'childCtrl',
        controllerAs: 'child',
        template: '<p>{{ child.greeting.hello }}</p>', // PREFIX WITH VALUE
                                                       // OF `controllerAs`
        require: ['myChild', '^myParent'],
        link: function(scope, elem, attrs, ctrls) {
            var myChild = ctrls[0], myParent = ctrls[1];
            myChild.greeting = myParent.greeting;
        }
    }
});

答案 1 :(得分:1)

我发现你可以使用元素属性将属性从父指令控制器的范围传递给子节点。

function parentCtrl () {
  this.greeting = 'Hello world!';
}

function myParentDirective () {
  return {
    scope: {},
    controller: 'parentCtrl',
    controllerAs: 'ctrl',
    template: '<my-child greeting="ctrl.greeting"></my-child>'
  }
}

function childCtrl () {}

function myChildDirective () {
  return {
    scope: {
      greeting: '='
    },
    bindToController: true,
    controller: 'childCtrl',
    controllerAs: 'ctrl',
    template: '<p>{{ ctrl.greeting }}</p><input ng-model="ctrl.greeting" />'
  }
}

angular.module('parent', [])
  .controller('parentCtrl', parentCtrl)
  .directive('myParent', myParentDirective);

angular.module('child', [])
  .controller('childCtrl', childCtrl)
  .directive('myChild', myChildDirective);

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