miechooy miechooy - 5 months ago 10
AngularJS Question

Directive in directive Angular

I am new to AngularJS and I am trying to create directive which contains another directive inside.

Here how first directive look like

(

function () {
app.directive("cmEventBar", function () {

var controller = function () {
var vm = this;
vm.events = [
{name: "Truckdriver1", eventId: 1 },
{name: "Truckdriver2", eventId: 1 },
{name: "Truckdriver3", eventId: 1 }
];
}

return {
templateUrl: "app/shared/eventsBar/eventBar.html",
restrict: "E",
controller: controller,
priority: 1000,
terminal: true,
controllerAs: "vm",
scope: {}
};
});
})();


Inside html of this directive I am using ng-repeat to show all events. Insinde ng-repeat I have another directive:

<div ng-repeat="item in vm.events">
<cm-single-event name="{{item.name}}" eventId="{{item.eventId}}"></cm-single-event>
</div>


Here how second directive look like:

(function () {
app.directive("cmSingleEvent", function () {

var controller = function () {
var vm = this;
vm.info = switchEvent(eventId);
}

return {
template: "<li class={{vm.info.itemClass}}> {{vm.name}} {{vm.info.messege}} </li>",
restrict: "E",
controller: controller,
controllerAs: "vm",
scope: {
name: "=",
eventId: "="
}
};
});
})();


The output is a little weird because event has 3 elements and in output I see only one element + there are no vm.info from directive inside.

Output


{{vm.name}} {{vm.info.messege}}


What am I doing wrong here?

Thanks in advance!

Answer

As you are using = for name & eventId, you should not use {{}} while assigning there value in attribute & cmSingleEvent directive should have bindToController: true to retrieve value from isolated scope to controller this(context)

<cm-single-event name="item.name" event-id="item.eventId"></cm-single-event>