[AngularJS] Accessing The View-Model Inside The link() When Using controllerAs

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>

 

posted @ 2015-09-09 01:17  Zhentiw  阅读(225)  评论(0编辑  收藏  举报