AngularJS拦截ng-switch并做点什么?

时间:2015-03-05 06:19:04

标签: angularjs

我有两个在元素指令中的视图。要确定显示哪一个,它由我的应用程序主控制器中的单个范围变量控制。每当" ng-switch"更改范围变量" a",执行一些特定的功能集?

$ scope.watch有替代品吗?我正在寻找性能最低的解决方案。

1 个答案:

答案 0 :(得分:0)

您可以使用ng-if创建/销毁HTML元素,尽管它不像哲学那样有角度。 HTML:

<div ng-init="runAInstructions()" ng-if="runInstruct">0</div>
<div ng-init="runBInstructions()" ng-if="!runInstruct">1</div>

<div ng-click="runInstruct = !runInstruct">Click here!</div>

JS:

    $scope.runInstruct = true;

    $scope.runAInstructions = function(){
        console.log("A");
    }
    $scope.runBInstructions = function(){
        console.log("B");
    }

或者,您只需执行按下按钮时在控制器中确定的功能A或B,然后按下#34;单击此处&#34;。所以删除ng-init,然后写成:

<div ng-click="determineInstruct()">Click here!</div>
JS中的

    $scope.determineInstruct = function(){
        ($scope.runInstruct) ? $scope.runAInstructions() :  $scope.runBInstructions();
    }

或者最后,简单地在每个函数中确定,避免使用第三个函数,将其写成:

<div ng-if="runA()">0</div>
<div ng-if="!runB()">1</div>


    $scope.runA = function(){
        if ($scope.runInstruct){
            console.log("run A instructions here")
        }
        else
            return false;
    }

    $scope.runB = function(){
        if (!$scope.runInstruct){
            console.log("run B instructions here")
        }
        else{
            return false;
        }
    }

您还可以使用ng-hide / ng-show,它不会破坏元素,并会在每个$ digest周期进行评估。