2

I'm trying to modify a variable inside $scope within a controller's function and the affectation works, but didn't apply in the view.

app.controller('LoginCtrl', ['$scope', '$http', function ($scope, $http) {

    $scope.test = "test";

    $scope.logIn = function() {
        // This changes the value to test2, but does not applies it to the view.
        $scope.test = "test2";
    };

}]);

In the login.html:

  DEBUG: {{ test }}

And the routeProvider:

$routeProvider
    .when('/', {
        templateUrl: '/views/login.html',
        controller: 'LoginCtrl'
    })

Is something I miss out the documentation ?

Thanks !

4
  • Can you please provide a Plunker with a demo of the problem. It's working for me: plnkr.co/edit/xbZWsE2i422BrDLDYXI3?p=preview Commented Dec 18, 2014 at 0:52
  • Please at least include the full HTML. No way to tell if you've assigned ng-controller or ng-app correctly. Commented Dec 18, 2014 at 0:58
  • Your code does not demonstrate that the logIn function is actually getting called to change value on the scope. Commented Dec 18, 2014 at 1:50
  • I am facing the same issue. how did you get through this? Commented Sep 28, 2015 at 6:21

3 Answers 3

3

This happens because angular is not aware of the scope changes made by logIn function which i think is called asynchronously in your case. After calling logIn() asynchronously, force scope changes by

$scope.$apply()
Sign up to request clarification or add additional context in comments.

1 Comment

Where should it be placed ? Cause in this case, it means I have to apply every HTTP responses with it ?
0

So I think this is a reference or inheritance issue that is known with primitives see this post https://github.com/angular/angular.js/wiki/Understanding-Scopes. Try this same code but put test inside an object like so:

$scope.viewModel = {};
$scope.viewModel.test = 'Test';

1 Comment

This doesn't fix my issue. Thank you anyway !
0

I found out that I put ng-controller="" in the HTML element that calls the logIn() function.

In fact, I called it twice and causes the view update to fail.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.