2017-09-11 113 views
0

爲什麼我得到的錯誤:$ ctrl沒有定義從下面的自定義指令?我沒有在指令中的控制器中定義$ ctrl。AngularJS自定義指令 - bindToController錯誤

var myapp = angular.module('plunker', []); 
myapp.directive('userinfo', function() { 
    return{ 
     restrict:'E', 
     template: 'User : <b>{{$ctrl.user.firstName}}</b> <b>{{$ctrl.user.lastName}}</b>', 
     scope:{ 
     user: '=' 
     }, 
     bindToController:true, 
     controller:function(){ 
     var $ctrl = this; 

     }, 

     controllerAs:$ctrl 
    } 
    return directive; 
}); 
myapp.controller("MyController", function() { 
    var $ctrl = this; 
    $ctrl.jakob = {}; 
    $ctrl.jakob.firstName = "Jakob"; 
    $ctrl.jakob.lastName = "Jenkov"; 

    $ctrl.john = {}; 
    $ctrl.john.firstName = "John"; 
    $ctrl.john.lastName = "Doe"; 
}); 

回答

3

controllerAs應該是字符串,但是您傳遞的是未定義的全局變量$ ctrl。試試這個:

controllerAs: '$ctrl' 

From the docs

If it is necessary to reference the controller or any functions bound to the controller from the template, you can use the option controllerAs to specify the name of the controller as an alias.