Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular. restrict: 'A' directive. Pass object

Is there a way to pass configuration object into custom directive which defined as a attribute-directive?

I've got an object in Controller that I want to send to directive:

$scope.configObject = {
    count: 5,
    mode: 'fast',
    getData: myService.getData // function of external service that avaliable in controller
}

In my View I declare directive:

<div class='list-class' my-list='configObject'></div>

Directive looks like:

return {
    restrict: 'A',
    link: function(scope, elem, attrs) {
        var config = angular.fromJson(attrs.myList);
    }
}

i've tried to get config object using angular.getJson - but it doesn't work for functions (it's possible to get only count and mode). Is .getJson() the incorrect way to get config?

Also (I guess it's not even possible) - is there a way to get config object avoiding accessing to

attrs.myList

directly? I mean if I change initializing of directive from

.directive('myList', function() { ... }) to
.directive('myCustomList', function() { ... })

shall I change accessing to

attrs.myCustomList

because view would look like

<div class='list-class' my-custom-list='configObject'></div>
like image 295
user1820686 Avatar asked Dec 15 '22 17:12

user1820686


2 Answers

you can pass it using isolate scope if you want

return {
    restrict: 'A',
    scope: { config : '=myList' }
    link: function(scope, elem, attrs) {
        //access using scope.config
    }
}

or as already answered you can parse it from attrs

      $parse(attrs["myList"])(scope);

and yes if you change the directive to myCustomList, you will have to change the code

    scope: { config : '=myCustomList' }

or

      $parse(attrs["myCustomList"])(scope);
like image 188
harishr Avatar answered Jan 11 '23 16:01

harishr


You can use $parse service to fetch the config object.

(function(){
    var directiveName = 'myList';
    angular.module('YourModule').directive(directiveName,['$parse',function($parse){
        return {
            restrict: 'A',
            link: function(scope, elem, attrs) {
                var config = $parse(attrs[directiveName])(scope);
            }
        };
    }]);
})();
like image 29
Shripal Soni Avatar answered Jan 11 '23 16:01

Shripal Soni