指令中的AngularJS Service被调用两次

时间:2015-08-02 19:54:02

标签: angularjs angularjs-directive angularjs-service

我试图找出我的指令是否被初始化两次而不是一次,如果有更好的方法来初始化和观察更改。

我的angular index.html的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>

我有一个指令,通过服务从AJAX调用中获取数据,然后像这样初始化指令模板,

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

我有一个选择框,用户可以在其中更改城市,然后需要更新指令以显示新城市信息。我编写了我的指令来跟踪这样的变化,

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);
            });
    }
});

我注意到当页面加载时,上面的两个函数都被调用,因为控制台打印了

Initializing the template for the first time
Going to change the city to, Chicago
  1. 这是否意味着该指令被初始化两次?
  2. 是否有办法调用范围。$ watch仅在选择下拉列表的值发生变化时(即选定的城市变化)?
  3. 我是否需要初始化'selectedcity'的值以避免指令被初始化两次?
  4. 有更好的方法吗?

1 个答案:

答案 0 :(得分:1)

根据docs,您应检查$ watch表达式中的newValue !== oldValue

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
  }
}