6

I have the following controller:

app.controller('MyCtrl', function($interval, $scope) {
    $scope.foo = 2;
    $interval(function() {
        console.log($scope.foo);
    }, 1000);
});

And the following code in my view:

<input type="text" ng-model="foo" />

When I load the page, the input is correctly populated with the value "2". However, if I change the value in the input, the console continues to log "2" (without quotes).

I've used an $interval just to illustrate - with $watch() the callback only fires once and then never again. If I use ng-change="" on the input, then $scope.foo in the callback is always equal to 2.

What am I doing wrong?

5
  • Nothing wrong with this fragment of code, you've wrote. Check example: plnkr.co/edit/vaK63tDaBhnVLk4rC11z?p=preview. How do you instantiating your controllers and app? Commented Jun 13, 2015 at 12:22
  • @Andrey I use $routeProvider to create a route to MyCtrl: $routeProvider .when('/my', { templateUrl: 'tpl/my.html', controller: 'MyCtrl' }) And app is instantiated as var app = angular.module('app', ['ngRoute', 'ngCookies']); Commented Jun 13, 2015 at 12:24
  • Can you provide mcve? Commented Jun 13, 2015 at 12:28
  • This is a small part of a larger ng app, but judging by the fact that your plunker worked, I think there's something else somewhere in app which is interfering. Commented Jun 13, 2015 at 12:34
  • Read about angular dot rule. Commented Jun 13, 2015 at 12:34

1 Answer 1

13

If you use ng-model, you have to have a dot in there .

Bind model by creating a object like this

controller

$scope.form={
   foo:0
};

view

<input type="text" ng-model="form.foo" />
Sign up to request clarification or add additional context in comments.

5 Comments

That works great. Are you able to explain to me what made you suggest this?
sometimes angular push scope in upper layer in your controller scope. if you bind direct varable into model then this variable can be add into newly added scope by which is current scope. but if you use bind by object property then whatever scope may push by angular the relation between object doesn't break
@NeilGarb A decent blog post from a while back covers 5 AngularJS Anti-Patterns and Pitfalls. The first on the list is forgetting the dot.
You saved my time brother.
THANKS! I'm maintaining an old angular application. I introduced a new property in the scope and I've been struggling for weeks to understand why my property did not update. I created an object and put the property as a child on that object; now all works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.