11

I've created a directive which works perfectly fine. Now after bumping angular to 1.5.0, I figured this directive is a typical example of what could be written using the new .component() notation.

For some reason, the require property no longer seems to work.

The following is a simplified example:

angular.module('myApp', [])

.component('mirror', {
  template: '<p>{{$ctrl.modelValue}}</p>',
  require: ['ngModel'],
  controller: function() {
    var vm = this;
    var ngModel = vm.ngModel;
    
    ngModel.$viewChangeListeners.push(onChange);
    ngModel.$render = onChange;

    function onChange() {
      vm.modelValue = ngModel.$modelValue;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp">
  <input ng-model="someModel"/>
  <mirror ng-model="someModel"></mirror>
</div>

I also tried using require as a simple string:

...
require: 'ngModel'
...

and as an object:

...
require: {
  ngModel: 'ngModel'
}
...

I've looked at the docs for $compile and component, but I can't seem to get it to work.

How can I require other directive controllers in an AngularJS 1.5 component?

4

1 回答 1

20

$onInit在 Angular 1.5 的组件语法中,在调用组件的生命周期方法之前,您无法访问所需的控制器。所以你需要把你的初始化移到那里,这是你的代码片段的一个工作版本,我在其中添加了$onInit函数。

angular.module('myApp', [])

.component('mirror', {
  template: '<p>{{$ctrl.modelValue}}</p>',
  require: {
    ngModel: 'ngModel',
  },
  controller: function() {
    var vm = this;
    
    vm.$onInit = function() {
      var ngModel = vm.ngModel;
      ngModel.$viewChangeListeners.push(onChange);
      ngModel.$render = onChange;
    };
    
    function onChange() {
      vm.modelValue = vm.ngModel.$modelValue;
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp">
  <input ng-model="someModel"/>
  <mirror ng-model="someModel"></mirror>
</div>

于 2016-04-08T18:01:50.200 回答