Angularjs $范围变量未在视图中更新

时间:2014-03-28 16:06:45

标签: javascript angularjs

我是Angularjs的新手,我试图在两个单独的函数中更新两个$ scope变量,这些函数在ng-click上调用。

即使变量更新,它们也不会在视图中重新绑定。

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>

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);
    };

}

我创造了一个小提示,告诉你我的意思:http://jsfiddle.net/M3pZ8/

任何人都可以告诉我这样做的正确方法是什么?

提前致谢。

2 个答案:

答案 0 :(得分:12)

这是因为你有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>

答案 1 :(得分:0)

更新了您的jsfiddle

 don't need to add same controller multiple times.