angularjs bindToController值在控制器中未定义

时间:2017-02-16 12:21:44

标签: angularjs angularjs-directive

我在我的指令上使用controllerAs并使用了bindToController。 但是bindToController参数在控制器上是未定义的。 DEMO

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

2 个答案:

答案 0 :(得分:1)

您的演示按预期工作。初始化期间未定义父控制器$scope.fullname。只有在change按钮被击中后它才会收到值。查看更新的演示:http://jsfiddle.net/10fmrb8n/

答案 1 :(得分:0)

问题是您在指令控制器的init上执行了console.log(this.name)..但只有当您单击按钮并调用$ scope.change时,$ scope.fullname才会填充值功能..如果你想要它不是未定义你要做的事情:

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

初始化它