Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs - how do i access directive attribute in controller

I am new to angularjs and i am stuck in accessing directive attributes in controller.

Directive

<rating max-stars="5" url="url.json"></rating>

app.directive('rating', [function () {
    return {
        restrict: 'E',
        scope: {
            maxStars: '=',
            url: '@'
        },

    link: function (scope, iElement, iAttrs) {
     console.log(iAttrs.url); //works
}

controller

app.controller('ratingController', ['$scope', '$attrs' , '$http','$routeParams',function  ($scope,$attrs,$http,$routeParams) {


            console.log($attrs.url); //shows undefined

}]);

How do i access the url attribute in controller?

like image 631
Arun Avatar asked Jul 21 '14 12:07

Arun


2 Answers

If you want to associate a controller with a directive, you can use the Directive Definition Object's controller property (either specifying the controller as a function or specifying the name of the controller (in which case it can be registered anywhere in your module)).

app.directive('rating', [function () {
    return {
        restrict: 'E',
        scope: {
            maxStars: '=',
            url: '@'
        },
        controller: 'ratingController'
    };
});

// Meanwhile, in some other file
app.controller('ratingController', function ($scope, $element, $attrs) {
    // Access $attrs.url
    // Better yet, since you have put those values on the scope,
    // access them like this: $scope.url
    ...
});

When using two-way data-binding via =, the corresponding attribute's value should not be a literal (because you can't have two-way data-binding to a literal), but a string specifying the name of a property in the current scope.

Using <rating max-stars="5"... together with scope: {maxStars: '='... is wrong.
You hould either use <rating max-stars="5"... and scope: {maxStars: '@'...
or <rating max-stars="someProp"... and scope: {maxStars: '='... while the enclosing scope has a property named someProp with a numeric value (e.g. $scope.someProp = 5;).

like image 151
gkalpak Avatar answered Sep 27 '22 02:09

gkalpak


app.directive('myDirective',function(){

  return{

    controller: function($scope,$attrs){
        console.dir($attrs);
    }

  }

});

That's it. If you want to access the elements attributes on a controller, you have to set up a controller for the directive.

(You could however, use a shared service to make those attributes available to another controller, if that's want you want to achieve)

like image 23
Wottensprels Avatar answered Sep 27 '22 02:09

Wottensprels