最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular.js : How to bind "change" event to service - Stack Overflow

programmeradmin0浏览0评论

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>

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>
Share Improve this question asked Feb 25, 2014 at 14:04 thomasthomas 1,4631 gold badge18 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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/api/ng/directive/ngChange

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() {});
    
发布评论

评论列表(0)

  1. 暂无评论