mmbb
mmbb

Reputation: 337

Set variable when object changes in Angular

I'm using Angular and attempting to show a button to a form only when the object changes that the form manipulates.

html:

<input ng-model="form.field1" />
<input ng-model="form.field2" />
<div ng-show="formChanged">Show button</div>

controller:

$scope.form = {
    field1: 'hello'
}
$scope.$watch('form', function(){
    $scope.formChanged = true;
});

I was under the impression that $watch would fire whenever any part of the object changed. It seems, however, that the $watch is called at the very beginning and only once after the object changes.

I have a plunker here: http://plnkr.co/edit/Hv8oLLviOzSLMUg2iBXt

Parenthetical information: I have found that if I set $watch to explicitly look at each property that the $watch functions as I expect it to, though it still is run at the beginning.

To stop it from being called at the beginning I've tried to use the newValue and oldValue variables as follows:

$scope.$watch('form', function(newVal, oldVal){});

but that doesn't work either.

Upvotes: 0

Views: 3041

Answers (1)

Stewie
Stewie

Reputation: 60406

Use $dirty property from the FormController, or set the third parameter on $watch callback to true for object equality comparison.

Solution A:

<form ng-submit="submit()" name="myForm">
  <div>
    <input type="email" name="email" ng-model="formData.email" required />
    <span ng-show="myForm.email.$dirty && myForm.email.$error.required">required</span>
  </div>

  <div>
    <button ng-show="myForm.$dirty" type="submit">Submit</button>
  </div>
</form>

Solution B:

$scope.$watch('form', function(){
  $scope.formChanged = true;
}, true);

Upvotes: 2

Related Questions