我试图找出我的指令是否被初始化两次而不是一次,如果有更好的方法来初始化和观察更改。
我的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
答案 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
}
}