我知道这是一个范围问题,但我似乎无法弄明白。我想通过按下按钮将一个div改成另一个div。换句话说,ng-click
将执行ng-switch
激活所需的更改。
但是,我的按钮都嵌套在各自的ng-switch-when
div
内,所以我假设这是问题所在。
以下是我正在谈论的内容:http://jsfiddle.net/gGKGX/8/
提前谢谢!
答案 0 :(得分:2)
在Angular中,ng-switch创建一个新范围,这意味着在ng-switch
构造中设置的变量不能在其外部访问。
在当前场景中,您已在控制器中使用thingToShow
定义$parent.thingToShow
,如
<button ng-click="$parent.thingToShow='two'">Switch!</button>
答案 1 :(得分:1)
你可以让ngClick调用一个更新范围thingToShow
的函数。
JS:
angular.module("myApp",[]).controller("MainController", function($scope) {
$scope.thingToShow = "one";
$scope.showThing = function (thing) {
$scope.thingToShow = thing;
};
});
查看:
<div ng-controller="MainController" ng-app="myApp">
<div ng-switch="thingToShow">
<div ng-switch-when="one">
Showing Thing One
<button ng-click="showThing('two')">Switch!</button>
</div>
<div ng-switch-when="two">
Showing Thing Two
<button ng-click="showThing('one')">Switch!</button>
</div>
</div>
</div>
答案 2 :(得分:0)
除了其他答案,您还可以使用对象值(因为字符串之类的东西不会通过交换机设置的隔离范围传递)http://jsfiddle.net/gGKGX/14/
// dom
<div ng-switch="thingToShow.val">
<div ng-switch-when="one">
Showing Thing One
<button ng-click="thingToShow.val = 'two';">Switch!</button>
</div>
<div ng-switch-when="two">
Showing Thing Two
<button ng-click="thingToShow.val = 'one';">Switch!</button>
</div>
</div>
// Ctrl
$scope.thingToShow = {val: "one"};