我正在使用jquery在表单中添加动态字段,但是当我尝试从该动态字段获取值时,我没有任何值。
Javascript / AngularJs
var myApp = angular.module('myApp',[]);
myApp.controller('demoController',['$scope',function($scope){
$scope.submitForm = function(){
console.log($scope.book);
alert($scope.book);
}
}]);
function getHidden(){
var inputHtml = '<input type="text" name="sessionDate" id="sessionDate" ng-model="book.sessionDate" ng-init="1233">';
$('#addInput').html(inputHtml);
}
在上面的示例中,getHidden()将在表单中添加动态字段,并且alert / console.log()将显示该字段的值。
html代码:
<div ng-app="myApp" ng-controller="demoController">
<form id="demoForm" name="demoForm" ng-submit="submitForm()">
<div id="addInput"></div>
<input type="text" ng-init="demoModel='hi'" ng-model="book.demoModel" name="demoModel" />
<a href="javascript:void(0)" onClick="getHidden()">Add Field</a>
<button type="submit">Submit</button>
</form>
</div>
要添加新的动态字段,请单击“添加字段”。在字段中输入一些值,然后按Submit,以便在控制台中获得预加载的文本框的值,而不是动态添加的字段值。
请检查jsFiddle链接以获取完整示例:https://jsfiddle.net/krishna91/b6nk7x4d/47/
答案 0 :(得分:0)
AngularJS
有自己的jQuery
子集,称为jQLite的实现。因此,请勿同时使用JQuery
和AngularJs
。您可以仅使用AngularJs
来实现此功能,如下所示。希望它对您有帮助:
var myApp = angular.module("myApp", []);
myApp.controller("demoController", [
"$scope",
function($scope) {
$scope.arr = [
'text here'
];
$scope.addItem = function() {
$scope.arr.push('text here');
};
$scope.submitForm = function() {
console.log(1, $scope.arr);
};
}
]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="demoController">
{{arr}}
<form id="demoForm" name="demoForm">
<div id="addInput" ng-repeat="x in arr track by $index">
<input type="text" ng-model="arr[$index]" />
</div>
<button ng-click="addItem()">Add Field</button>
<button ng-click="submitForm()">Submit</button>
</form>
</div>