IfOnly
IfOnly

Reputation: 540

watch not working properly in angularJS

I have written watch on pubInfoKey, But its not working properly when I set value to pubInfoKey in select function. What can be the problem here, I want to call Controller changeState method on pubInfoKey value change

Directive's link function :

link: function(scope, element, attrs, ngModelCtrl, state) {
var pubInfoKey;
scope.$watch('pubInfoKey', function(val) {
    if (val) {
        $scope.changeState(val);
    }
}
);

var autoSuggest = element.autocomplete({

select: function(event, ui) {
    var i = 0;
    for (i = 0; i < scope.sug.length; i++)
    {
        if (scope.sug[i] === ui.item.value.toString())
        {
            pubInfoKey = scope.suggestionKey[i];
            break;
        }
    }
}
});                             
}

Controller :

$scope.sug = [];
$scope.suggestionKey = [];
$scope.changeState = function(value) {
                //some code
            };

Upvotes: 0

Views: 161

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32357

$watch checks for scope properties on each $digest

  • When I run your code I get SyntaxError: Unexpected token }
  • You also need pubInfoKey to be a property on a scope
  • If autocomplete is a jQuery plugin then you need to trigger a $digest:
var autoSuggest = element.autocomplete({
  select: function(event, ui) {
    var i = 0;
    for (i = 0; i < scope.sug.length; i++) {
      if (scope.sug[i] === ui.item.value.toString()) {
        scope.$apply(function(){        
          scope.pubInfoKey = scope.suggestionKey[i];          
        })
        break;
     }
    }
  }
});

Upvotes: 1

Related Questions