標籤:
If u using controller & controllerAs in directive, then the link()‘s 4th param ‘controller‘ will refer to the controller u defined before.
function MessageController(){ var vm = this; vm.message = "Hello"; }function greeting(){ function link(scope, element, attrs, ctrl){ ctrl.message = ctrl.message + ‘ ‘ + scope.name; } return { controller: ‘MessageController‘, controllerAs: ‘vm‘, link: link, scope: { name: ‘@‘ }, template: ‘<h1>{{vm.message}}</h1>‘ };}angular.module(‘app‘, []) .directive(‘greeting‘, greeting) .controller(‘MessageController‘, MessageController);
<!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title></head><body ng-app="app"><greeting name="Zhentian"></greeting></body></html>
[AngularJS] Accessing The View-Model Inside The link() When Using controllerAs