1

I am using controllerAs on my directive and used bindToController. But bindToController parameter is undefined on controller. 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 Answers 2

1

Your demo works as expected. Parent controller $scope.fullname is undefined during initialization. It receives value only after change button is hit. See updated demo: http://jsfiddle.net/10fmrb8n/

Sign up to request clarification or add additional context in comments.

Comments

0

Hi the problem is that you do a console.log(this.name) on the init of the directive controller .. but $scope.fullname is filled with value only when you click the button and call the $scope.change function .. if you want it is not undefined you've to do something like:

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 initialize it

1 Comment

how can access a parameter at initialization time? I need it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.