abottoni
abottoni

Reputation: 525

AngularJS directive called twice fail

I am having (probably) a really easy issue, but the thing is that I had spent more time than expected trying to solve it and i haven't done it yet.

My directive in the application is hard to replicate, so, for the purpose of simplicity I made a script in JSFiddle with a simple directive but with the same result.

Essentially, the problem is related to a directive that have been called twice using different options on each. The result is that the directive rendered always takes the value of the first set of options (and sometimes only with the second set).

My HTML:

<div ng-controller="MyCtrl">
    <button-menu options="options1" />
    <button-menu options="options2" />
</div>

My options (In the controller):

// Button Options        
$scope.options1 = {
    id: "1",
    buttonTemplate: "<span style=\"font-size:16pt\">Button 1</span>"
};

$scope.options2 = {
    id: "2",
    buttonTemplate: "<span style=\"font-size:10pt\">Button 2</span>"
};

I have no idea what I am doing wrong, but actually this is the first time that I need a directive running at least twice in a same page, so probably I am missing something.

Any ideas?

Thanks

Upvotes: 1

Views: 5427

Answers (2)

Andrei
Andrei

Reputation: 4617

Here is an updated fiddle that works: http://jsfiddle.net/DewZb/4/

First for a weird reason you need a closing tag for button-menu:

<button-menu options="options1"></button-menu>
<button-menu options="options2"></button-menu>

Create an isolated scope:

scope: {options: '='}

Then in the link function:

scope.buttonOptions = scope.options;

Upvotes: 6

Erstad.Stephen
Erstad.Stephen

Reputation: 1035

The scope is shared between the same custom directives on the page. You can setup the directive to have an isolated scope.

The reason you are seeing them take the first or second is because the linking is happening at different times depending on how the angular compile ordered them. This is because they both have the same priority.

http://www.ng-newsletter.com/posts/directives.html

Upvotes: 2

Related Questions