我有两个在元素指令中的视图。为了确定显示的是哪一个,它由我的应用程序主控制器中的单个范围变量控制。有没有办法每当"ng-switch“改变作用域变量"a”时,执行一些特定的函数集?
有没有$scope.watch的替代品?我正在寻找一种性能密集度最低的解决方案。
发布于 2015-03-05 15:12:02
您可以使用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周期中进行计算。
https://stackoverflow.com/questions/28871258
复制相似问题