如何在AngularJS中动态更新视图
How to dynamically update view in AngularJS
我有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;
};
}]);
上面的代码不起作用,因为即使在单击Do stuff并显示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>
正在更新作用域。但可能的问题是ng-show
,你正在使用"{{notation}}"
设置一个字符串,它总是成为真理(即使它是"真"或"假"),只是直接使用表达式。
<div ng-show="{{states['currentState'] == 'A'}}">
<div ng-show="states.currentState === 'A'">
从医生
: -
ngShow expression -如果表达式为真,则分别显示或隐藏该元素。
你很接近了。它不能工作的原因是属性"ng-show"不需要"{{" "}}"符号来工作。
我刚刚构建了你的代码,但把那些拿走了,它正在工作,你描述你想要它。
<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>
相关文章:
- d3基于用户选择动态更新节点
- 如何从相应的控制器动态更新标题和描述
- 根据CHECKBOX输入值动态更新DIV信息
- HTML动态更新滑块输入
- 如何使用ajax和jquery动态更新数组表
- 如何动态更新输入值属性
- 动态更新chartJ中的图表
- 动态更新Angular2指令中自定义属性的值
- jQuery动态更新数据键和值
- 如何在jQuery的.on()方法中动态更新按钮的ID选择器
- 使用 php/jquery 动态更新单个模态
- 在 Ionic 中动态更新滚动区域
- 具有动态更新的实时标题 (AJAX+jQuery)
- jQuery:动态更新 N 个最新值的列表
- 如何动态更新选择值
- 将URL路径与<a>attr('href')来动态更新.active类
- Jquery调整大小动态更新
- 在javascript中动态更新嵌套对象
- javascript中的文本框未正确动态更新
- 动态更新Ace Editor+Requirejs的语法高亮显示