moshi
moshi

Reputation: 294

Angular binding does not change

i have this controller and this view (html). if i give an initial value to $scope.article.Context, it will be shown in the view. (means that the view recognizes the controller). when i change the $scope.article.Context value inside a controller function, i dont see it changing in the view. any idea ? Thanks !!!

controller:

angular.module('generalApp', [])
    .controller('menuController', function ($scope, $http) {

        $scope.article = {Context:"initial value"}  ;

        $scope.menuLinkSelected = function (articleId) {
            $http.post("Home/GetArticle?articleId=" + articleId).then(function (response) {
                $scope.article.Context = "new value";
                $scope.$apply();
            });
        };

html:

<body ng-app="generalApp">

<div ng-controller="menuController">
    <div ng-include="'partials/topMenu.html'"></div>
    <div ng-include="'partials/sideMenu.html'"></div>

    <div ng-model="article">
        <label>{{article.Context}}</label>
    </div>

    <input type="button" value="click" onclick="ziba()" />
</div>

Upvotes: 0

Views: 91

Answers (2)

aludvigsen
aludvigsen

Reputation: 5981

Solution:

<div>
   <label ng-bind="article.Context"></label>
</div>

You're ng-model doesn't do anything when you assign it to that div.

JSFiddle :

Here you have a working jsfiddle using your example.

Upvotes: 1

Jake McGuire
Jake McGuire

Reputation: 304

Are you sure that your $http POST request is actually returning? You could test this by changing your controller to update $scope.article.Context like this:

var timerFn = function(){
  $scope.article.Context = "It works!";
};

$timeout(timerFn, 1000);

If that's the issue, you may want to try using this $http syntax to handle your POST request's callback:

$http.post('someUrl')
     .success(function(data, status){
       console.log(data);
     })
     .error(function(data, status){
       console.log(data);
     });

Sidenotes:

(1) You can probably just set your ng-model in the DOM to "article.Context" although what you have should work.

(2) You don't need to call $scope.$apply() inside of Angular. It's only used to update bindings when changes occur outside of Angular.

Upvotes: 1

Related Questions