Angular.js:基于对象数组中的子字符串禁用ng-ng

时间:2014-08-14 23:58:23

标签: javascript angularjs input

在我的项目中,我有一些待办事项。如果用户输入带有子串clean的待办事项,则应禁用输入,因此清洁,清洁,清洁等输入应禁用输入。

在我的角度控制器中,我编写了这个方法来禁用基于子串的输入。

$scope.disableInput = function (todos) {
    todos.forEach(function (item) {

        if (item.toLowerCase().indexOf('clean') > -1) {

            return true;
        } else {

            return false;
        }
    });
};

在我的html文件中,我已将ng-disabled添加到输入中。

    <form ng-submit="addTodo();">
        <input type="text" ng-model="todoText" ng-disabled="disableInput(todos)">
        <input type="submit" value="add">
    </form>

如果我手动将其设置为true,它会起作用,但它不会响应disableInput方法的返回值。我想在每次提交新项目时检查todos对象,并根据子字符串禁用。

如何将true方法中的disableInput值返回给模板,以便输入被禁用?

JSFiddle version

here采用了完整的示例,并添加了禁用功能。

1 个答案:

答案 0 :(得分:1)

在你的函数(下面)中,你正在迭代一个集合并在第一个对象上返回一个bool,这应该响起一些铃声。

$scope.disableInput = function (todos) {
todos.forEach(function (item) {

    if (item.toLowerCase().indexOf('clean') > -1) {

        return true;
    } else {

        return false;
    }
});

};

'我想在每次提交新项目时检查待办事项对象'

听起来像是一个明智的地方,在添加待办事项时执行的功能中添加了检查。

现在你不必迭代你的待办事项。

var disableInput = function (input) {
    if(input.toLowerCase().indexOf('clean') > -1){
        return true;
    }
    return false;
};

因此,您需要向范围添加变量以跟踪输入是否已禁用。

$scope.disabled;

现在在你的addTodo函数中(从你的小提琴中抓取)你应该添加对刚刚输入的'clean'字符串的检查。

 $scope.addTodo = function() {
    $scope.todos.push({
       text:$scope.todoText,
       done:false
     });

     //Set the scope variable you just made to the result of the above function
     $scope.disabled = disableInput($scope.todoText);

     $scope.todoText = '';
  };

最终在你的加价中;将禁用的变量分配给ng-disabled。

<input type="text" ng-model="todoText"  size="30"
 placeholder="add new todo here" ng-disabled="disabled">

这是我以前修改过的小提琴。

jsFiddle

希望有所帮助