thomas thomas - 1 month ago 9
AngularJS Question

Angular.js : How to bind "change" event to service

First of all, I'm new to angular.js...

I have a HTML5 page where I can add new URLs with a name. Now, I want to have a check to a back-end service to check if the URL already exist. How can I bind the “onChange” event on the input boxes to a service function?
I have tried to find the solution, but I have not been able to find anything that describes this easily.

<div ng-controller="newLink">
<input class="url" value="{{Url}}" ng-model="Url" placeholder="Please type a URL"/>
<input class="name" value="{{Name}}" ng-model="Name" placeholder="Type a name" />
<div class="status"></div>
</div>
<script>
app.controller('newLink', ['$scope', 'appService', function ($scope, appService) {
$scope.Name = '';
$scope.Url = '';
}]);
</script>

Answer

You can use the ngChange directive

<input ng-change="onChange()">

// in controller

$scope.onChange = function(){
  // call your service function here
}

For further information, see: http://docs.angularjs.org/api/ng/directive/ngChange