【问题标题】:Can't use ngChange in ngRepeat - Angularjs不能在 ngRepeat 中使用 ngChange - Angularjs
【发布时间】:2015-03-13 12:50:39
【问题描述】:

我正在使用 ngRepeat 生成复选框字段集。

我这样做如下:

<fieldset id="country_select" ng-controller="CountriesListController">
        <span ng-repeat="country in countries">
          <label>
            <input type="checkbox" id="country.name" ng-change="locationAdd(country.name)">
            {{country.name}}
          </label><br/>
        </span>
</fieldset>

但是由于某种原因,将 ngChange 指令添加到我的复选框会导致我的 ng-repeat 输出仅显示一个复选框,如下所示:

复选框 {{country.name}}

当我将 ngChange 更改为 ngClick 时,我的 ngRepeat 循环有效。

所以我的问题是:为什么 ngChange 不能与 ngRepeat 一起使用,但 ngClick 在插入到我的复选框输入中时会起作用

我在控制台中收到以下错误:

Error: [$compile:ctreq] Controller 'ngModel', required by directive 'ngChange', can't be found!
http://errors.angularjs.org/1.3.7/$compile/ctreq?p0=ngModel&p1=ngChange
at REGEX_STRING_REGEXP (http://localhost:9000/bower_components/angular/angular.js:63:12)
at getControllers (http://localhost:9000/bower_components/angular/angular.js:7535:19)
at nodeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7724:33)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7073:13)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7076:13)
at compositeLinkFn (http://localhost:9000/bower_components/angular/angular.js:7076:13)
at publicLinkFn (http://localhost:9000/bower_components/angular/angular.js:6952:30)
at $get.boundTranscludeFn (http://localhost:9000/bower_components/angular/angular.js:7091:16)
at controllersBoundTransclude (http://localhost:9000/bower_components/angular/angular.js:7747:18)
at ngRepeatAction (http://localhost:9000/bower_components/angular/angular.js:24524:15)angular.js:11592 (anonymous function)angular.js:8542 $getangular.js:14241 $get.Scope.$digestangular.js:14486 $get.Scope.$applyangular.js:9644 doneangular.js:9834 completeRequestangular.js:9775 requestLoaded

【问题讨论】:

  • 检查浏览器控制台是否有错误。
  • 请将整个代码粘贴到jsfiddle中
  • 我已经为你们添加了我的控制台错误

标签: javascript angularjs checkbox angularjs-ng-repeat


【解决方案1】:

ng-change 需要ng-model。您在复选框上缺少 ng-model

检查此plunker 以获取工作示例。

【讨论】:

  • 谢谢你!你可能知道为什么 ng-change 指令需要 ng-model 吗?
  • 我在 Angular 文档中看到的只是:注意,这个指令需要 ngModel 存在。
  • 它是必需的,因为它在内部检查是否为 ng-model 提交了新值。如果是,那么只有它会评估 ng-change。此外,需要 ng-model 来维护控件的状态,如脏、无效等,这在表单提交或需要 ng-model 时很有用,如果您想将所选复选框的值访问到范围内。
  • 哦,这完全有道理。谢谢你教我更多关于 Angular 的知识。
【解决方案2】:

小心您打算使用ngChange。就我而言,我的手指和眼睛有点太快了,当我打算使用 data-ng-click 时,没有发现 Intellisense 选择了 data-ng-change

我很确定在输入 data-ng-c 后我只看到了一个条目(data-ng-click);但也许 Intellisense 在显示其他选项时有点慢,当我点击 [Tab] 时首先按字母顺序选择...

【讨论】:

    猜你喜欢
    • 2014-06-24
    • 2023-04-02
    • 2013-10-27
    • 2013-05-29
    • 1970-01-01
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    相关资源
    最近更新 更多