Question

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>
Was it helpful?

Solution

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

OTHER TIPS

Two simple solutions to this problem:

  1. use ng-change directive:

    <input ng-change="doSomething()">
    
    $scope.doSomething = function() {};
    
  2. $watch value change

    <input ng-model="Url">
    
    $scope.$watch('Url', function() {});
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top