gh9
gh9

Reputation: 10703

Angular JS and passing complex object array as attribute to directive

I am having trouble passing this complex object array through an attribute to a directive. What I am doing wrong and why is it wrong?

jsfiddle

Cut and pasted code

<div ng-controller="MyCtrl">
    <pass-object obj="obj"></pass-object>
</div>

var myApp = angular.module('myApp',[]);

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div ng-repeat="foo in foos">Hello, {{foo.prop}}!</div></div>'
    };
});

myApp.controller('MyCtrl', function ($scope) {
    $scope.obj = [{ prop: "hello" }, {prop: "world"}];
});

Upvotes: 2

Views: 885

Answers (2)

Patrick
Patrick

Reputation: 6948

You are iterating over foos in your directive template. You didn't pass in foos, you passed in obj. Try this:

myApp.directive('passObject', function() {
    return {
        restrict: 'E',
        scope: { obj: '=' },
        template: '<div ng-repeat="o in obj">Hello, {{o.prop}}!</div></div>'
    };
});

Updated fiddle.

Upvotes: 5

dfsq
dfsq

Reputation: 193271

There is no scope property named foos, it should be obj according to your scope definition scope: { obj: '=' }:

template: '<div ng-repeat="foo in obj">Hello, {{foo.prop}}!</div></div>'

Or you can change scope config to:

scope: { foos: '=obj' },

Upvotes: 3

Related Questions