简体   繁体   中英

AngularJS: Model not updating in controller scope

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?

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" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM