如何使用 AngularJS ng-model 创建数组

2023-12-26

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

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

但我无法访问 $scope.telephone


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

$scope.telephone = [];

为了解决附加新输入时 ng-model 不被识别的问题 - 为此,您必须使用$compile角度服务。

来自$compile 上的 Angular.js API 参考 http://docs.angularjs.org/api/ng.%24compile:

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

看看JSFiddle http://jsfiddle.net/V4BqE/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 AngularJS ng-model 创建数组 的相关文章

随机推荐