我正在使用AngularJS,并尝试创建一个表单,在其中可以动态添加新输入,类似于此小提琴:http://jsfiddle.net/V4BqE/(下面的主HTML,小提琴中的工作代码)。
<div ng-app="myApp" ng-controller="MyCtrl">
<div add-input>
<button>add input</button>
</div>
</div>
我希望能够为表单使用HTML模板,因为要添加的输入行长约为300行。我的问题是,在模板中使用时,我无法弄清楚如何索引包含数据的范围变量。我试图在plnkr http://plnkr.co/edit/4zeaFoDeX0sGTuBMCQP2?p=info上对上述代码进行修改。但是,当我单击按钮时,没有表单元素出现。
在线(plnkr),我的template.html找不到404,但是我认为这只是plnkr的限制。在装有Python HttpServer的计算机上,使用
Error: [$parse:syntax]
方法时,我得到了$templateRequest
的TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
和$http.get
。有关使索引范围变量数组与外部html文件一起使用的任何建议?
谢谢,JR
编辑:更新plnkr链接
最佳答案
您可以在没有指令和外部模板的情况下进行操作
您要执行的操作不需要指令(实际上,使用基本的angularjs工具非常简单)
http://plnkr.co/edit/LVzGN8D2WSL2nR1W7vJB?p=preview
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<div ng-repeat="item in telephoneNumbers">
<hr>
<input type="text" ng-model="item.phone">
</div>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
如果您坚持使用指令,
http://plnkr.co/edit/BGLqqTez2k9lUO0HZ5g1?p=preview
phone-number.template.html
<div>
<hr>
<input type="text" ng-model="ngModel" >
</div>
html
<body>
<div class="container" ng-app="myApp" ng-controller="MyCtrl">
<button class="btn btn-primary" type="button" ng-click="addPhoneInput()">add input</button>
<form>
<phone-number ng-repeat="item in telephoneNumbers" ng-model="item.phone"></phone-number>
</form>
<hr>
<div class="well">
<h4>Phone Numbers,</h4>
<p ng-repeat="item in telephoneNumbers">{{item.phone}}</p>
</div>
</div>
</body>
js
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
// Define $scope.telephone as an array
$scope.telephoneNumbers = [];
$scope.addPhoneInput = function() {
$scope.telephoneNumbers.push({});
};
// This is just so you can see the array values changing and working! Check your console as you're typing in the inputs :)
$scope.$watch('telephoneNumbers', function(value) {
console.log(value);
}, true);
}]);
app.directive('phoneNumber', function(){
return {
replace:true,
scope: {
ngModel: '=',
},
templateUrl: "phone-number.template.html"
}
});
关于javascript - 具有索引范围变量数组的AngularJS动态模板,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30666319/