user3296211
user3296211

Reputation: 203

Angularjs directive - isolated scope not working

I have created a directive myToolbar that should dynamically create and append toolbarItems, triggered by an event. Each toolbarItem is passed different data.

Please, check out this jsfiddle:

The output is "baz baz baz" but it should be "foo bar baz".

Each toolbarItem has a isolated scope, but the toolbarData of all toolbarItems is overwritten by the last one.

What did I wrong?

I have a solution (jsfiddle link). But this can't be the way to go in angular.

I serialized the the toolbarData and wrote it to the toolbarItem markup.

Does someone know a clean solution?

Upvotes: 0

Views: 716

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32357

You are recompiling all the toolbar-items on each call:

  • You should get a reference to the newly created element.
  • You should only compile once each toolbar-item

Solution:

Here is a working fork: http://jsfiddle.net/q8bUK/

scope.$on('addToolbarItem', function (e, toolbarData) {
    var newElm = angular.element('<toolbar-item>a</toolbar-item>');
    element.append(newElm);
    newElm.attr("toolbarData", JSON.stringify(toolbarData));                
    $compile(newElm)(scope);
});

Upvotes: 1

Related Questions