AngularJS术语长度检查

时间:2015-08-04 17:27:02

标签: angularjs

我将从后端获取User,因此我将在输入字段中输入一个名称,然后调用Controller Method getUserByTerm。 这很好用。 我现在的问题是,如果实现没问题,或者Angular的其他支持是否更容易?目前,if(term.length> 3)看起来很像" Javascript- like"。 谢谢你的帮助!

angular
    .module('project.management')
    .controller('ManagementController', ManagementController);

function ManagementController() {
    var vm = this;
    vm.getUsersByTerm = getUsersByTerm;

    function getUsersByTerm(term) {
        if(term.length > 3) {
            alert('get User By term: ' + term);
        }
    }
};


<div ng-controller="ManagementController as vm">
<form class="well form-search">
    <label>Usersuche:</label>
    <input type="text" ng-change="vm.getUsersByTerm(term)" ng-model="term" class="input-medium search-query" placeholder="Username">
    <button type="submit" class="btn" ng-click="vm.getUsersByTerm(term)">Suchen</button>
</form>
<pre ng-model="result">
    {{result}}
</pre>
   </div>

1 个答案:

答案 0 :(得分:0)

您可以在输入中添加ng-maxlength="3",并仅在表单有效时提交(https://docs.angularjs.org/api/ng/input/input%5Btext%5D

虽然,您的代码非常简单,但可能不需要。

<form class="well form-search" ng-submit-"vm.getUsersByTerm(term)">
    <label>Usersuche:</label>
    <input type="text" ng-change="vm.getUsersByTerm(term)"
     ng-model="term" ng-maxlength="3" class="input-medium search-query" placeholder="Username">
    <button type="submit" class="btn">Suchen</button>
</form>