简体   繁体   中英

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?

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM