c f
c f

Reputation: 196

AngularJS Service in directive being called twice

I'm trying to figure out if my directive is being initialized twice instead of once and if there is a better way to initialize and watch for changes.

HTML code for my angular index.html:

<!-- Select drop down-->
<select name="selectcity" ng-model="selectedcity" ng-options="key as value for (key , value) in cities"></select>

<!--Directive-->
<div simple-chart chart-data="lineData"></div>

I have a directive that gets its data from an AJAX call via a service and then initializes the directive template like so,

MyService.getData(scope.selectedcity).then(
function (data) {
//code goes here
console.log("Initializing the template for the first time");
scope.lineData.push(data.info);
});

I have a select box where the user can change the city and then the directive needs to be updated to show the new citys information. I have coded my directive to track the changes like so,

scope.$watch('selectedcity', function (nv) {
    if (scope.lineData !== undefined) {
        //code goes here
        console.log("Going to change the city to, "+nv);
        //Going to call the service for the new city
        MyService.getData(nv).then(
            function (data) {
                //code goes here
                console.log("Initializing the template for the first time");
                scope.lineData.push(data.info);
            });
    }
});

I have noticed that when the page loads, both the functions above are called because the console prints,

Initializing the template for the first time
Going to change the city to, Chicago
  1. Does it mean that the directive is being initialized twice?
  2. Is there a way to call scope.$watch only when the value of the select drop-down changes (i.e. selected city changes)?
  3. Do I need to initialize the value of 'selectedcity' to avoid the directive from being initialized twice?
  4. Is there a better way of doing this?

Upvotes: 1

Views: 700

Answers (1)

juco
juco

Reputation: 6342

As per the docs you should check whether the newValue !== oldValue in your $watch expression:

scope.$watch('selectedcity', function (newValue, oldValue) {
  if (newValue && newValue !== oldValue) {
    // We have a new value set, and it's not the same as the old.
    // Do something
  }
}

Upvotes: 1

Related Questions