0

I basically have a very complicated set of tabs with various input controls but lets not worry about this for now. For now let consider simple input wtching issue I am baffled by.

For example:

<input type="text" placeholder="Associate some tags please" data-ng-model="tag" data-ng-maxlength="250">

I am try to detect if user has typed something into my input:

$scope.$watch('tag', function () {
//$scope.$watchCollection('tag', function () {
    console.log('tag changed');
});

But I seem to get zero response. However, when I perform my save operation I always seem to get the value user typed in.

Is a case of ng-model not binding correctly or is it that I am not $watching it correctly?

Also after I've performed my save operation I try to clear what user typed in for the tag with:

$scope.tag = '';

But that doesn't seem to work for some reason as though $scope.tag doesn't exist.

PS: When I say save operation I am actually performing a array.push() into an object which later gets saved by a service.

For example:

$scope.checkSaveTag = function (tag) {
    ...
    // checked for duplicate tag beforehand
    $scope.myForm.Tags.push(tagObj); // complicated form object
    $scope.tag = ''; // tag input control
    ...
};
iiminov
  • 969
  • 1
  • 15
  • 34

2 Answers2

1

Any chance that the tag is an object or an array? If that is the case, you'll need to do a deep $watch, e.g:

$scope.$watch('tag', function () {
    console.log('tag changed');
}, true);
Jon Snow
  • 3,682
  • 4
  • 30
  • 51
  • 1
    Why did you die , Jon Snow ?? :'( – Anik Islam Abhi Jun 29 '15 at 08:17
  • @JonShow I tried that too but nothing changed. It would seem that I cannot read my model from inside my controller ``$scope.tag``. Very strange. – iiminov Jun 29 '15 at 08:37
  • The tag might be getting declared on a child scope instead. Try declaring something like `$scope.obj = {}` and set the ng-model to `obj.tag` and then watch the `obj.tag` instead. – Jon Snow Jun 29 '15 at 09:33
  • You're welcome, you can refer to http://stackoverflow.com/questions/17606936/angularjs-dot-in-ng-model to see why not having a dot in your ng-model can be a pitfall. – Jon Snow Jun 29 '15 at 10:00
  • I see, I will certainly dig a bit more into this when I have a bit of spare time. Thank you for pointing me in the right direction. – iiminov Jun 29 '15 at 10:03
1

Try like this

Controller

$scope.form={
 tag:''
}

$scope.$watch("form.tag",function(newVal,oldVal){
  console.log(newVal);
})

Html

<input type="text" placeholder="Associate some tags please" data-ng-model="form.tag" data-ng-maxlength="250">
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
  • Sorry buddy but @JonShow got there a bit ahead of you. But both of you are absolutely correct. By encapsulating number of free form inputs that I had problem with into scoped object I am able to ``$watch`` them. – iiminov Jun 29 '15 at 10:00