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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:39:23  来源:igfitidea点击:

Angularjs $scope variables not updating in view

javascriptangularjs

提问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 MainCtrldeclared 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>

回答by Anoop

Updated your jsfiddle

更新了你的jsfiddle

 don't need to add same controller multiple times.