Reputation: 27394
I have a savingIndicator
directive that will show a spinny, and then success / error messages. It binds to things like saving
and message
to show information to the user. The directive is pretty dumb and literally just loads a template like so
m.directive('savingIndicator', function () {
return {
restrict: 'E',
templateUrl: '/templates/savingindicator'
};
});
SavingIndicator.html (snippet):
<span ng-show="saving">
<img src="/Content/loader.gif" style="vertical-align: middle;" /> Saving...
</span>
In my current controller I have a number of things that need to save, so I want to separate them like so:
var thingToSave1 = {
saving: false,
message: ""
}
var thingToSave2 = {
saving: false,
message: ""
}
How can I tell savingIndicator
not to look on the main scope (the controller) for its variables, but inside one of these objects? In my head it would work something like what is below, but its not currently working
<input text="Save item 1" />
<saving-indicator ng-model="thingToSave1"></saving-indicator>
...
<input text="Save item 2" />
<saving-indicator ng-model="thingToSave2"></saving-indicator>
Upvotes: 0
Views: 61
Reputation: 336
You need to add another parameter in the directive's definition. The parameter you need is called "scope". Check out Angular's documentation is already explained there. If you want to play a little bit, this is a plunker (from angular docs):
...
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer-iso.html'
};
http://plnkr.co/edit/XFy6IB0cdBTMglItIgWR.
In that way you are specifying a new scope for the directive instead of using the controller one.
Upvotes: 1
Reputation: 4189
A quick hack would be as follows:
m.directive('savingIndicator', function () {
return {
restrict: 'E',
templateUrl: '/templates/savingindicator',
scope: {
myModel: '='
}
};
});
//---------------
<span ng-show="myModel.saving">
<img src="/Content/loader.gif" style="vertical-align: middle;" />Saving...
</span>
//---------------
<saving-indicator my-model="thingToSave1"></saving-indicator>
You can learn more about directives and isolate scope option in Angular docs.
Upvotes: 1