Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to the controller scope from a directive inside ng-repeat?

I'm a new user of AngularJS and I'm getting stuck when I have to access to a variable in a controller from a directive inside a ng-repeat. I think it has to be something related to scopes.

Here's my fiddle: http://jsfiddle.net/Zzb58/1/

The 'MyCtrl' scope has two properties: "items", an array, and "thing", just a string.

function MyCtrl($scope) {
    $scope.items = [{id: 'item1'}, {id: 'item2'}];    
    $scope.thing = "thing";
}

So, if I create a directive and I want it to read the array's content, this one works perfectly:

<div my-directive ng-repeat="item in items" item='item'></div>
app.directive('myDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            item: '=item',
        },
        template: '<div>{{ item.id }}</div>'
    }
});

The HTML is refreshed properly.

But if I try to access to the "thing" variable from the directive, it is always read as "undefined".

app.directive('myDirective', function () {
    return {
        restrict: 'AE',
        scope: {
            item: '=item',
            thing: '='
        },
        template: '<div>{{ item.id }} - Here is not the {{thing}}</div>'
    }
});

I think the problem has to be related to the scope child created in the ng-repeat, or maybe the variable is not being bound correctly.

However, If I use $parent.thing in the template, the variable is read and it's evaluated properly, but I don't know if that $parent is the ng-repeat scope or 'MyCtrl' scope.

1) What am I doing wrong?

2) Why is it needed to put the "item" element read in the ng-repeat as an attribute of the HTML element? I first thought "items" was in the parent scope, so when the isolated scope of the directive is created, I would just have to do something like "items: '='".

like image 930
Jorge Avatar asked Oct 02 '22 11:10

Jorge


1 Answers

By assigning an object to it, you create an isolate scope. If you set scope : true, you can use it like in your example, if not you have to pass it as an attribute, like you did with item.

http://jsfiddle.net/Zzb58/2/

For an explanation of different modes of scope, you can read the directives section on this page: https://github.com/angular/angular.js/wiki/Understanding-Scopes

Generally but especially when working with inherited scope values, I would also highly recommend using an object with a property set, instead of a simple string-variable, as this might lead to a detachment throughout the scopes due to how prototypical inheritance works.

like image 127
hugo der hungrige Avatar answered Oct 13 '22 11:10

hugo der hungrige