0

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for this, on some occasions I don't have a model to pass in (i.e. im using the current scope) how do I pass in the current one if I don't have a thingToSave. <saving-indicator saving-model> didnt seem to work
Sorry but I'm not following you. Could you try to explain a little bit or give more information?
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.