javascript Angularjs $scope 变量未在视图中更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22717842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs $scope variables not updating in view
提问by Mr.Haze
I'm new to Angularjs and im trying to update two $scope variables in two seperate functions which are called on ng-click.
我是 Angularjs 的新手,我试图在两个单独的函数中更新两个 $scope 变量,这些函数在 ng-click 上调用。
Even though the variables update, they wont rebind in the view.
即使变量更新,它们也不会在视图中重新绑定。
HTML
HTML
<div ng-app="">
<div ng-controller="MainCtrl">
<p> <a href="#" ng-click="getDetails();getElse()">Refresh</a> </p>
<p ng-controller="MainCtrl"><span ng-bind="something"></span></p>
<p ng-controller="MainCtrl"><span ng-bind="somethingelse"></span></p>
</div>
</div>
JSfunction MainCtrl($scope) {
JS函数 MainCtrl($scope) {
$scope.something = "something";
$scope.somethingelse = "else";
$scope.getDetails = function () {
alert("getdetails before change: "+$scope.something);
$scope.something = 'changed';
alert("getdetails: "+$scope.something);
};
$scope.getElse = function () {
alert("getElse before change: "+$scope.somethingelse);
$scope.somethingelse = 'changed';
alert("getElse: "+$scope.somethingelse);
};
}
I've created a fiddle to show you what i mean: http://jsfiddle.net/M3pZ8/
我创建了一个小提琴来向您展示我的意思:http: //jsfiddle.net/M3pZ8/
can anyone tell me what is the correct way to do this?
谁能告诉我这样做的正确方法是什么?
Thanks in advance.
提前致谢。
回答by tymeJV
It's because you have MainCtrl
declared 3 times, effectively creating 3 separate scopes. You only need it once, at the top.
这是因为您已经MainCtrl
声明了 3 次,有效地创建了 3 个独立的作用域。您只需要一次,在顶部。
<div ng-controller="MainCtrl">
<p> <a href="#" ng-click="getDetails();getElse()">Refresh</a> </p>
<p><span ng-bind="something"></span></p>
<p><span ng-bind="somethingelse"></span></p>
</div>