Reputation: 196
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
Upvotes: 1
Views: 700
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