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?

kumar kundan
  • 2,027
  • 1
  • 27
  • 41
Neil Garb
  • 197
  • 1
  • 10
  • Nothing wrong with this fragment of code, you've wrote. Check example: http://plnkr.co/edit/vaK63tDaBhnVLk4rC11z?p=preview. How do you instantiating your controllers and app? – Andrey Jun 13 '15 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']); – Neil Garb Jun 13 '15 at 12:24
  • Can you provide [mcve](http://stackoverflow.com/help/mcve)? – Andrey Jun 13 '15 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. – Neil Garb Jun 13 '15 at 12:34
  • Read about angular dot rule. – dfsq Jun 13 '15 at 12:34

1 Answers1

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" />
Community
  • 1
  • 1
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • That works great. Are you able to explain to me what made you suggest this? – Neil Garb Jun 13 '15 at 12:31
  • 2
    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 – Anik Islam Abhi Jun 13 '15 at 12:39
  • @NeilGarb A decent blog post from a while back covers [5 AngularJS Anti-Patterns and Pitfalls](http://nathanleclaire.com/blog/2014/04/19/5-angularjs-antipatterns-and-pitfalls/). The first on the list is forgetting the dot. – Eric McCormick Jun 14 '15 at 12:48
  • 2
    You saved my time brother. – Sanjay Gupta Feb 04 '16 at 09:58
  • 1
    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! – mortb Mar 01 '21 at 13:59