2017-02-16 4 views
1

Ich verwende controllerAs auf meine Anweisung und verwendet bindToController. Aber der Parameter bindToController ist auf dem Controller nicht definiert. DEMOangularjs bindToController Wert ist nicht definiert in Controller

var myApp = angular.module('myApp',[]); 

myApp.controller('MyController', function($scope){ 

    $scope.change = function(){ 
     $scope.fullname = 'Brian Kim'; 
    } 
}); 

myApp.directive('myDirective', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     name: '=' 
    },  
    controller: function() { 
     console.log(this.name); // undefined 
    }, 
    controllerAs: 'ctrl', 
    bindToController: true, 
    template: '{{ctrl.name}}', 
    }; 
}); 

Antwort

1

Ihr Demo funktioniert wie erwartet. Der übergeordnete Controller $scope.fullname ist während der Initialisierung nicht definiert. Es empfängt nur Wert, nachdem change Knopf gedrückt wird. Siehe aktualisierte Demo: http://jsfiddle.net/10fmrb8n/

0

Hallo das Problem ist, dass Sie tun, um eine console.log (this.name) auf der init der Richtlinie Controller .. aber $ scope.fullname wird mit dem Wert gefüllt nur, wenn Sie auf die Schaltfläche klicken und rufen Sie die $ scope.change Funktion .., wenn Sie es wollen, ist man so etwas nicht undefiniert haben zu tun:

var myApp = angular.module('myApp',[]); 

myApp.controller('MyController', function($scope){ 
    $scope.fullname = 'Brian Kim'; //<-- HERE YOU INITIALIZE IT 

    $scope.change = function(){ 
     $scope.fullname = 'Brian Kim'; 
    } 
}); 

myApp.directive('myDirective', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     name: '=' 
    },  
    controller: function() { 
     console.log(this.name); 
    }, 
    controllerAs: 'ctrl', 
    bindToController: true, 
    template: '{{ctrl.name}}', 
    }; 
}); 

So initialisieren

+0

wie einen Parameter bei der Initialisierung zugreifen kann? ich brauche es – barteloma

Verwandte Themen