在我的项目中,我有一些待办事项。如果用户使用子字符串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,并添加了disable功能。

最佳答案

在下面的函数中,您要遍历一个集合并在第一个对象上返回布尔值,这应该会引起一些麻烦。

$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

希望能有所帮助

10-07 13:46
查看更多