【问题标题】:Ng-Model with Ng-If Doesn't work (Very basic example) [duplicate]带有 Ng-If 的 Ng-Model 不起作用(非常基本的示例)[重复]
【发布时间】:2018-12-07 09:17:39
【问题描述】:

我有这个非常简单的代码。 filterOption = 'Account ID' 并且值正确时出现输入。但是ng-model 不起作用,我在 pre 中看不到任何东西

<pre>{{test}}</pre> // doesnt work
<pre> {{filterOption}}</pre> // this shows Account ID
<input ng-if="filterOption == 'Account ID'" ng-model="test" required>

【问题讨论】:

  • ng-if 创建自己的范围。使用$parent. 到达控制器范围,因此您需要ng-model="$parent.test"
  • 使用$parentcode smell,这是更深层次问题的征兆。
  • 遵循始终使用 '.' 的“最佳实践”,可以轻松避免原语的这个问题。在你的 ng 模型中

标签: javascript html angularjs


【解决方案1】:

ng-if 有自己的子作用域,允许它销毁和恢复作用域元素。因此,您的模型需要到达父作用域(通常是控制器),这可以通过 $parent 前缀完成

这是一个例子:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app>

  <input type="text" ng-if="true" ng-model="a"> Doesn't work
  <br>
  <input type="text" ng-if="true" ng-model="$parent.a"> Works
  <br> 
  {{a}}

</div>

【讨论】:

  • 使用$parentcode smell,这是更深层次问题的症状。当数据和ng-model 之间有多个子作用域时,它将不起作用。最好使用命名对象。请参阅此Youtube video。 Misko 演示了 ng-switch 的原始绑定问题。
【解决方案2】:

检查这个。 ng-if 创建自己的范围。因此,如果您想将 ng-model 与 ng-if 一起使用,请使用 $parent

<!DOCTYPE html>
<html ng-app="abc">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-controller="myCtrl">
<pre>{{test}}</pre> // doesnt work
<pre> {{filterOption}}</pre> // this shows Account ID
<input ng-if="filterOption == 'Account ID'" ng-model="$parent.test" required>

</div>
<script>
var app=angular.module('abc',[]);
app.controller('myCtrl',function($scope){
$scope.filterOption="Account ID";
});
</script>
</body>
</html>

【讨论】:

  • 使用$parentcode smell,这是更深层次问题的症状。当数据和ng-model 之间有多个子作用域时,它将不起作用。最好使用命名对象。请参阅此Youtube video。 Misko 演示了 ng-switch 的原始绑定问题。
【解决方案3】:

您需要使用控制器来访问模板中的属性。 这里的例子: https://stackblitz.com/edit/sof-angularjs-5jwgpu?file=home%2Fhome.html

【讨论】:

    【解决方案4】:

    确定控制器的范围并使用 controllerAs 分配它们可以解决此问题。请参阅https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md 以获得更好的编码风格,这样您就不会遇到这些问题。

    <!DOCTYPE html>
    <html ng-app="abc">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <body>
    
    <div ng-controller="MyCtrl as vm">
    <pre>{{vm.test}}</pre> // doesnt work
    <pre> {{vm.filterOption}}</pre> // this shows Account ID
    <input ng-if="vm.filterOption === 'Account ID'" ng-model="vm.test" required>
    
    </div>
    <script>
    
    var app=angular.module('abc',[]);
    
    app.controller('MyCtrl',MyCtrl);
    
    function MyCtrl($scope){
     var vm = this;
     vm.filterOption = "Account ID";
    }
    
    </script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 2015-11-21
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2016-09-12
      相关资源
      最近更新 更多