如何为文本框应用ng-if

问题描述 投票:2回答:2

Plunker.

在我的plunker我有两个文本框。我已经将ng-if应用于文本框。如果ng模型包含-1值,那么它需要离开该文本框并能够输入另一个值,如果它不是-1然后那里没有问题。我们可以继续。

但是如果我应用ng-if然后它隐藏文本框,但我不想隐藏,只是我想要隐藏值。

HTML: -

<input type="text" ng-if ="model !=-1"  ng-model="model"/>

js: -

  $scope.model = '-1';
  $scope.model1 = '1';
javascript jquery html css angularjs
2个回答
1
投票

实际上,ng-if指令在其为真时隐藏其父级。我想你实际上是在有人输入-1时更改文本框的值。所以使用$watch

var module = angular.module("myModule", []);

module.controller('myController', ['$scope', function($scope) {
$scope.model = '-1';
$scope.model1 = '1';
$scope.txtValue = 1;
$scope.$watch("txtValue", function (newVal) {
    if (newVal == '-1')
    {
        $scope.model1 = -1;
        $scope.txtValue = "";
    }
    else
    {
        $scope.model1 = newVal;
    }        
    });
}]);

HTML

<div ng-app="myModule">
<div ng-controller="myController">
    <input type="text" ng-model="txtValue"/>
</div>
</div>

并记得删除ng-if指令


0
投票

您可以添加另一个输入,该输入在ng-model包含-1时可见,并且该值为null,因此用户可以输入新值。

<div ng-app="myModule">
  <div ng-controller="myController">
    <input type="text" ng-if ="model !=-1"  ng-model="model"/>
    <input type="text" ng-if ="model1 !=-1"  ng-model="model1"/>
    <input type="text" ng-show="model ==-1" ng-model="model = null" >
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.