如何创建与AngularJS的NG-模型数组 [英] How to create an Array with AngularJS's ng-model

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

问题描述

我试图创建一个数组拿着电话,我有这个code

 <输入类型=文本NG模型=电话[0]/>
<输入类型=文本NG模型=电话[1]/>

但我不能访问$ scope.telephone


解决方案

的第一件事是第一次。您需要定义 $ scope.telephone 作为你的控制器的阵列,然后才能开始在视图中使用它。

  $ scope.telephone = [];

要解决NG-模式,当您添加一个新的输入不被识别的问题 - 对于工作,你必须使用 $编译角服务。

从上$的 Angular.js API参考编译


  

编译HTML字符串或DOM成模板,并产生一个模板函数,那么它可以用来链接在一起范围和模板


  //我采用了棱角分明的语法。使用jQuery将有同样的效果
//创建输入元素
VAR输入= angular.element('< D​​IV><输入类型=文本NG模型=电话['+ $ scope.inputCounter +']>< / DIV>');
//编译HTML和分配范围
VAR编译= $编译(输入)($范围内);

的jsfiddle

一起来看看

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

解决方案

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 = [];

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.

From the Angular.js API reference on $compile:

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

Have a look on JSFiddle

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

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