【问题标题】:Angular 1 ng-model not working on second input fieldAngular 1 ng-model 不适用于第二个输入字段
【发布时间】:2017-07-15 05:24:36
【问题描述】:

请在这方面帮助我,

我在 AngularJS 控制器中动态生成了两个输入字段。我会将第一个输入值放入第二个输入值,第二个输入字段是只读的。

如果第二个输入值大于 50,则应该可以看到除法。

<input type="number" ng-model="firstInput"><br/>
<!--Some code depend on input value -->
<input type="number" ng-value="firstInput" ng-model="secondInput" readonly><br/>
<div ng-if="secondInput>50">Hello</div>

在这里,我必须用第二个输入模型检查 div ng-if,而不是第一个输入。

【问题讨论】:

  • 它必须是只读的。

标签: javascript html angularjs


【解决方案1】:

如果你想使用两个变量,你可以将 firstInput 的值赋给 secondInput 使用 $watch 在你的控制器中像这样,

   $scope.$watch('firstInput', function() {
           $scope.secondInput = $scope.firstInput;
   });

演示

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
 $scope.$watch('firstInput', function() {
       $scope.secondInput = $scope.firstInput;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div ng-app="myApp" ng-controller="AppCtrl">
<input type="number" ng-model="firstInput"><br/>
<!--Some code depend on input value -->
<input type="number"  ng-model="secondInput"    readonly><br/>
<div ng-if="secondInput>50">Hello</div>
</div>

【讨论】:

  • 谢谢,@Sajeetharan,看起来不错。但是,我正在动态生成输入字段。在生成第一个输入字段时,我无法了解它上面的依赖输入字段。只有在生成第二个输入时,我才会知道它依赖于哪个输入。所以,我认为 $watch 在这种情况下不起作用。因为我还有 5 对这样的输入,它们相互依赖。是否可以对所有依赖输入应用 $watch?
  • 为什么要删除答案
【解决方案2】:

试试这个

 <input type="number" ng-model="firstInput"><br/>
 <input type="number" ng-value="secondInput = firstInput" ng-model="secondInput" readonly><br/> 
 <div ng-if="secondInput > 50">Hello</div>

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
 <div ng-app="myApp" ng-controller="AppCtrl">
<input type="number" ng-model="firstInput"><br/>
<!--Some code depend on input value -->
<input type="number" ng-value="secondInput = firstInput" ng-model="secondInput" readonly><br/>
<div ng-if="secondInput>50">Hello</div>
</div>

【讨论】:

  • @Naresh 你测试我的答案了吗?
猜你喜欢
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
相关资源
最近更新 更多