2017-02-16 44 views
1

我在我的指令中使用了controllerAs並且使用了bindToController。 但是,控制器上的bindToController參數未定義。 DEMOangularjs bindToController的值在控制器中是未定義的

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}}', 
    }; 
}); 

回答

1

您的演示程序按預期工作。初始化期間父控制器$scope.fullname未定義。它只在change按鈕被擊中後纔會收到值。看到更新的演示:http://jsfiddle.net/10fmrb8n/

0

嗨問題是,你在指令控制器的init上做一個console.log(this.name)..但$ scope.fullname只有當你點擊按鈕時填充值調用$ scope.change功能..如果你想它是不是未定義你已經做這樣的事情:

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}}', 
    }; 
}); 

所以初始化

+0

如何訪問在初始化時的參數?我需要它 – barteloma

相關問題