CarbonMan
CarbonMan

Reputation: 4490

Angular data-binding $watch

My web page looks like (abbreviated)

<HTML ng-app="scanning">
...
<BODY ng-controller="scanningController">
<INPUT id=R_name maxLength=50 size=35 ng-bind='BOOKING.R_NAME'>
</BODY>
</HTML>

My code is

function scanningController($scope){
    $scope.depot = depot;
    $scope.BOOKING = {R_NAME: ''};
    /* Does anything get changed. */
    $scope.$watch('BOOKING', function() { 
        ...
    }, true);
}

var scanningModule = angular.module('scanning', []);
scanningModule.controller('scanningController', scanningController);

The watch event does not get called when the user changes the value of R_NAME via the textbox. It does get called when the page initially loads, just not when values are changed by the user. I have forced the event to fire by using an interval timer, changing a test property and calling $digest. In that case when I debug I can see that nothing entered through the textbox has been stored on the object. So it seems that I have not setup databinding correctly.

Upvotes: 0

Views: 48

Answers (1)

Thomas Roch
Thomas Roch

Reputation: 1216

You should use ng-model for two-way binding instead of ng-bind.

<INPUT id="R_name" maxLength="50" size="35" ng-model="BOOKING.R_NAME">

You can also use ng-change instead of adding a $watch in your controller

<INPUT id="R_name" maxLength="50" size="35" ng-model="BOOKING.R_NAME" ng-change="onChange()">

Controller

function scanningController($scope){
    $scope.depot = depot;
    $scope.BOOKING = {R_NAME: ''};
    /* Does anything get changed. */
    $scope.onChange = function () { 
        ...
    };
}

Upvotes: 1

Related Questions