我正在使用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工具非常简单)
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);
}]);
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"
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句