Angularjs $ scope variables not updated

I'm new to Angularjs, and I'm trying to update two $ scope variables in two separate functions that are called on ng-click.

Although the variables are updated, they will not retell in the view.

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   function 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 created a fiddle to show you what I mean: http://jsfiddle.net/M3pZ8/

can someone tell me this is the right way to do this?

Thanks in advance.

+4
source share
2 answers

This is because you declared MainCtrl3 times, effectively creating 3 separate areas. You need it only once, at the top.

<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>
+12

jsfiddle

 don't need to add same controller multiple times.
0

Source: https://habr.com/ru/post/1533946/