AngularJS拦截ng开关并做些什么



我有两个视图在元素指令中。为了确定显示的是哪一个,它由我的应用程序主控制器中的单个作用域变量控制。当作用域变量"a"上的"ng开关"发生变化时,有没有办法执行一些特定的函数集?

有没有$scope.watch的替代方案?我正在寻找一个性能密集度最低的解决方案。

您可以使用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。因此,删除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循环中进行求值。

相关内容

最新更新