Search code examples
angularjsangularjs-directiveangularjs-controller

Angular binding directive's parameters to controller


I am having trouble binding directive's parameters (using isolated scope) to access them from the directive's custom controller.

Please check this fiddle (open the console, to see the logged results!) http://jsfiddle.net/xj9gqqxn/4/

<div ng-controller="appCtr">
  <div>
    <div custom-directive param="customer.name">
    <span>{{customer.name}}</span>
    <br/>
    <input type="text" ng-model="customer.name"/>
    </div>
  </div>
</div>

When i log inside the directive's link function the value gets logged accordenly, but when i do the same within the constructor function of the controller i see the value as undefined.

If someone know how to access directive's parameters values within the constructor function of the directive's controller, please share the answer or point where i am making a mistake.. sad for me I got no further clues...

Thanks


Solution

  • Well your controller has same scope as directive so this will work just fine:

    app.controller('customController', ['$scope', '$timeout' , function($scope,$timeout) {
        console.log("[customController:new] -  param value is: " + $scope.param);
    }])
    

    http://jsfiddle.net/pegla/xj9gqqxn/6/

    Also if you are searching for bindToController so directive $scope value is bound to controller instead of $scope, you could do this:

    bindToController: {
                param: '='
            },
    

    Updated fiddle: http://jsfiddle.net/pegla/xj9gqqxn/8/