防止 api 调用在指令中重复执行

prevent api call from execution repeatedly in directive

我正在通过指令进行 api 调用。有条件显示指令。我正在使用 ng-show 处理它。但是,当第一次 html 加载 api 调用时,即使 ng-show 标志为 false。

我只想在 ng-show 标志为 true 时进行 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> 

这是我想出的解决方案。这涉及在指令范围内的 ngShow 属性上注册监视,然后在 api 调用后取消注册。在这里查看我的 fiddle 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 可能不起作用,如果你一次又一次地显示隐藏元素。