如何使用 AngularJS 的 ng-model 创建数组 [英] How to create an Array with AngularJS's ng-model

查看:25
本文介绍了如何使用 AngularJS 的 ng-model 创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个保存电话的数组,我有这个代码

I'm trying to create an array holding telephones, i have this code

<input type="text" ng-model="telephone[0]" />
<input type="text" ng-model="telephone[1]" />

但我无法访问 $scope.telephone

But i can't access $scope.telephone

推荐答案

首先是第一件事.您需要在控制器中将 $scope.telephone 定义为数组,然后才能开始在视图中使用它.

First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view.

$scope.telephone = [];

要解决在附加新输入时无法识别 ng-model 的问题 - 为此,您必须使用 $compile Angular 服务.

To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service.

来自 Angular.js API 参考 $compile:

将 HTML 字符串或 DOM 编译为模板并生成模板函数,然后可以使用该函数将作用域和模板链接在一起.

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');
// Compile the HTML and assign to scope
var compile = $compile(input)($scope);

查看 JSFiddle

这篇关于如何使用 AngularJS 的 ng-model 创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆