0

In my code (snippet example below), I have a variable that is bound to an input box using the ng-model directive. Then, I have another variable that, for the purpose of my project, is dependent on that bound variable.

How do I keep (in the case of the example below) bar up to date when foo changes?

I tried using the $scope.$watch function call (which I show the syntax I used below), but the bound function does not get called when the user types something into the input box.

HTML

...
<div ng-controller="exampleController as ctr">
    ...
    <div><input type="number" ng-model="ctr.foo" /></div>
    <div>{{ ctr.bar }}</div>
</div>

Javascript

app.controller('ExampleController', function($scope){
    var local = this;        

    this.foo = 5;
    this.bar = 10;

    this.updateBar = function(){
        this.bar = this.foo * 2;
    };

    $scope.$watch('foo', function(){
        local.updateBar();
    });
});

Note: All of this is just example code to show what my problem is.

2 Answers 2

1

There is no need for $watch, if you use ng-change? ;)

<div ng-controller="exampleController as ctr">
...
  <div><input type="number" ng-model="ctr.foo" ng-change="ctr.updateBar()" /></div>
  <div>{{ ctr.bar }}</div>
</div>

More info: https://docs.angularjs.org/api/ng/directive/ngChange

Sign up to request clarification or add additional context in comments.

1 Comment

Didn't even know I could do that tbh. Thanks very much!
0

Try to use a scope function:

HTML

<div ng-controller="exampleController">
    ...
    <div><input type="number" ng-model="foo" /></div>
    <div>{{ bar() }}</div>
</div>

Javascript

app.controller('ExampleController', function($scope){      

    $scope.foo = 5;
    $scope.bar = function(){
          return  $scope.foo * 2;
    };

});

Comments

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.