0

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?

5
  • Why broadcast? Why element.append? honestly, have you read anything about angular yet? Because this can be done waaaay simpler Commented Feb 11, 2014 at 13:37
  • In my application I get the toolbarData via WebSockets. I have to build a toolbar with the toolbarData programmatically when it received. It's my first Angular Project. How can i make it better? Commented Feb 11, 2014 at 13:43
  • I would definitely use ng-repeat and bind an array on the scope - and you can then push or remove items from array and it will be propagated into the view right away Commented Feb 11, 2014 at 13:47
  • And it doesn't matter how the data is loaded, the $broadcast can be changed to bind a scope variable to myToolbar directive and it will update on the fly as you need Commented Feb 11, 2014 at 13:48
  • Thanks for your suggestion. I have refactored my app. Now I use ng-repeat to create the toolbarItems. Commented Feb 12, 2014 at 16:20

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.