AngularJS directives attributes access from the controller AngularJS directives attributes access from the controller angularjs angularjs

AngularJS directives attributes access from the controller


What works is, if you set

scope.text = $attrs.text;

inside the linking and the controller functions. This will only work initially, as there is no 2way- databinding. You can use $attrs.observe though.

See fiddle: http://jsfiddle.net/JohannesJo/nm3FL/2/


In an isolated scope, a local scope property defined with '@' can not be accessed in the linking function. As @remigio already mentioned, such local scope properties are undefined at that point. $attrs.$observe() or $scope.$watch() must be used to asynchronously obtain the (interpolated) value.

If you are passing a constant value in the attribute, (i.e., no interpolation required, i.e., the attribute's value doesn't contain any {{}}s) there is no need for '@' or $observer or $watch. You can use $attrs.attribute_name once as @hugo suggests, or if you are passing a number or a boolean and you want to get the proper type, you can use $scope.$eval($attrs.attribute_name) once.

If you use '=' to databind a local scope property to a parent scope property, the value of the property will be available in the linking function (no need for $observe or $watch or $eval).


Since Angular 1.3, you can use bindToController. Here is a sample on how I use it. Here, I add the attribute to scope and then use bindToController to use that inside the controller:

var module = angular.module('testApp', [])    .directive('testcomponent', function () {    return {        restrict: 'E',        template: '<div><p>{{text}} This will run fine! </p></div>',        scope: {            text: '@text'        },        controller: function () {            console.log(this.text);        },        controllerAs: 'vm',        bindToController: true    };});

Angular 1.3 introduces a new property to the directive definition object called bindToController, which does exactly what it says. When set to true in a directive with isolated scope that uses controllerAs, the component’s properties are bound to the controller rather than to the scope. That means, Angular makes sure that, when the controller is instantiated, the initial values of the isolated scope bindings are available on this, and future changes are also automatically available.