我正在从指令进行api调用。有条件显示指令。我正在使用ng-show处理它。但是当第一次html加载时,即使ng-show标志为false,也会执行api调用。
我想仅在ng-show标志为真时才进行api调用。更改此ng-show标志后,我不想拨打api电话。
我做过类似的事情。
angular.module("module").directive("customDirective", function(){
return {
templateUrl : "cutomTemplate.html",
replace : true,
scope : {},
link : {
apicall();
}
};
});
<custom-directive ng-show="value === 1"></custom-directive>
答案 0 :(得分:1)
这是我提出的解决方案。这涉及在指令范围内在ngShow属性上注册监视,然后在进行api调用后对其进行注册。在这里查看我的小提琴http://jsfiddle.net/cmyworld/u57dw8ws/
该指令现在看起来像:
angular.module("module").directive("customDirective", function () {
return {
scope: {
ngShow: '='
},
link: function (scope, element, attr) {
var observeFn = scope.$watch('ngShow', function (value) {
if (value) {
console.log('Making api call');
observeFn(); // degister after first callback,
}
});
}
};
});
ng-if
可能无效,如果您一次又一次隐藏该元素。