Angularjs Directives and Scopes (get string not obj)

Hi, I have a problem with my directive, I searched the forum for any solution, but I didn't find anything for me.

I have a directive in my html inside ng-repeat and it looks like this:

<custom-slide item="{{slides[$index]}}" pos='$index'  ></custom-slide>

      

I need to pass an element this way beacause I need to see if the value of that object has changed in my main controller.

My scope of authority is this:

 return {
restrict: 'E',
link: linker,
scope:{
    item: '@item',
    pos: '=pos'
    //slide: '@slide',

}

      

my problem is if i use scope.item then i get a string and not an objetc object.

{type:0, isSelected:'slide' ,param1:'',param2:' ',param3:' '}

      

But I am getting this as a string, any way to have this as an object, no need to parse

any advice !!? many thanks!

EDIT

I need to have an element as an object because in my layout I am modifying the directive template and in this template I have things like:

   <div>
   <div class="mainText">{{scope.item.param1}}</div>
   <div class="footer Text">{{scope.item.param2}}</div>
   </div>

      

so when {{scope.item.param1 }}

evaluated, the value is undefined because it is not an object

+3


source to share


3 answers


Try removing {{}} from the attr element:



<custom-slide item="slides[$index]" pos="$index"></custom-slide>

      

0


source


You should use =

if you are trying to chain an expression:

 return {
restrict: 'E',
link: linker,
scope:{
    item: '=',
    pos: '=pos'
    //slide: '@slide',

}

      



Then pass the expression in the attribute without curly braces:

<custom-slide item="slides[$index]" pos="$index" ></custom-slide>

      

0


source


You get a string because you are literally putting JSON into the DOM, which is a very bad idea and removes your ability to modify by reference.

Basically you cannot pass JSON as an attribute, there really is no reason. Here is a version of your directive that will only pass "how" you get data from the scope and use $ parse to get that data.

Html

<custom-slide item="slides[$index]}.item}" pos='$index'  ></custom-slide>

      

Directive

module.directive('customSlide', function($parse) {
    return {
        restrict: 'E',
        link: function(scope, element, attrs) {
            var pos = attrs.pos;
            var item = $parse(attrs.item)(scope);
        }
    }
});

      

0


source







All Articles