Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - 如何使用AngularJS的ng-model创建一个数组(How to create an Array with AngularJS's 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]" />

But i can't access $scope.telephone

(但我无法访问$ scope.telephone)

  ask by DelGiudice translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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定义为数组,然后才能在视图中开始使用它。)

$scope.telephone = [];

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.

(为了解决在附加新输入时无法识别ng-model的问题 - 为了使其工作,您必须使用$compile Angular服务。)

From the Angular.js API reference on $compile :

(来自$ compileAngular.js API参考 :)

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.

(将HTML字符串或DOM编译为模板并生成模板函数,然后可以将其用于将范围和模板链接在一起。)

// 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);

Have a look on JSFiddle

(看看JSFiddle)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...