【问题标题】:$scope doesn't update when using ng-if使用 ng-if 时 $scope 不会更新
【发布时间】:2016-01-28 17:49:17
【问题描述】:

在 Angular 1.3.x 上,我做了一个选择输入,它在 ng-change 上调用一个函数。周围有一个 ng-if 语句。

html

<div class="form-group" ng-if="property">
  <label for="city-picker">in</label>
  <select class='form-control focus input-sm' ng-model="cityIds" ng-options="city.id as city.name for city in cities" ng-change="getMetrics(cityIds)">
    <option value="">all</option>
  </select>
</div>

控制器

app.controller('MainCtrl', function($scope) {
  $scope.cities = [{
   name: "Amsterdam",
   id: 1
  },{ 
   name: "paris",
   id: 2
  }]
  $scope.property = true;
  $scope.getMetrics =  function(cityIds) {
    console.log(cityIds);
    console.log('$scope.cityIds is undefined: ', $scope.cityIds);
  }
});

当我更改选择字段时,会使用正确的 $scope 更新调用 ng-change 函数,但是 $scope 不会更新。

查看以下插件:http://plnkr.co/edit/sQaLts5xyGBjThjdQJwM

当我删除 ng-if 语句时,$scope 会被 select 输入正确更新。有人可以解释这种行为吗?

【问题讨论】:

标签: javascript angularjs angularjs-scope


【解决方案1】:

ng-if 指令创建一个原型继承自父范围的新范围。因此,您的 ng-model="cityIds" 正在这个新范围内更新 cityIds。

在父作用域中使用一个对象并从你的 ng-model 中引用它。

例如:

在你的控制器中,定义

$scope.data = {cityIds: null};

并且,参考模板中的内容

ng-model="data.cityIds"

这确保您始终在处理父作用域的数据。

【讨论】:

  • 或者使用'controller as'语法给控制器起一个名字并通过它访问模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 2013-06-25
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
相关资源
最近更新 更多