我有2个div
元素如下所示,我想根据在点击锚元素时在控制器中调用的doStuff()
函数只显示其中一个元素。
<div ng-controller='myController'>
<div ng-show="{{states['currentState'] == 'A'}}">
//displaying this div if the currentState is A
<a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="{{states['currentState'] == 'B'}}">
//displaying this div if the currentState is B
</div>
</div>
以下是控制器代码:
myApp.controller('myController', ['$scope', function($scope) {
var states = ['A', 'B'];
$scope.states = states;
$scope.states['currentState'] = $scope.states['currentState'] || 'A';
$scope.doStuff = function(stateToShow) {
//doing stuff
$scope.states['currentState'] = stateToShow;
};
}]);
上面的代码不起作用,因为即使单击执行内容并显示B 锚点元素,状态仍为“A”。
有人可以帮我理解为什么它不起作用?
app.js
//...
.state('home', {
url: '/',
views: {
'': { templateUrl: 'partials/index.html' },
'myView@home': {
templateUrl: 'partials/myView.html',
controller: 'VehicleController'
}
//other named ui views
}
})
//...
的index.html
<div class="main">
<div class="container">
<div class="row margin-bottom-40">
<div class="col-md-12 col-sm-12">
<div class="content-page">
<div class="row">
<div ui-view="myView"></div>
<!-- other named ui-views -->
</div>
</div>
</div>
</div>
</div>
</div>
myView.html
<div ng-controller='myController'>
<div ng-show="states['currentState'] == 'A'">
//displaying this div if the currentState is A
<a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="states['currentState'] == 'B'">
//displaying this div if the currentState is B
</div>
</div>
答案 0 :(得分:4)
正在更新范围。但问题可能是ng-show
你使用"{{notation}}"
设置一个字符串,它总是变得真实(即使它是“真”或“假”),只需直接使用表达式。
更改
<div ng-show="{{states['currentState'] == 'A'}}">
到
<div ng-show="states.currentState === 'A'">
<强> Demo 强>
来自Doc: -
ngShow表达式 - 如果表达式是真实的,那么元素将分别显示或隐藏。
答案 1 :(得分:1)
你非常接近。它不起作用的原因是属性&#34; ng-show&#34;不需要&#34; {{&#34; &#34;}}&#34;工作的符号。
我刚刚构建了你的代码但是把它们关掉了,它正如你所描述的那样工作。
<div ng-show="states['currentState'] == 'A'">
//displaying this div if the currentState is A
<a ng-click="doStuff('B')">Do stuff and show B</a>
</div>
<div ng-show="states['currentState'] == 'B'">
//displaying this div if the currentState is B
</div>