我有这个表单,用户可以上传文章,他可以选择添加一些共同作者。如果他想添加一个共同作者,他会点击一个按钮,该按钮将动态生成一个包含其他用户列表的下拉菜单。
问题是我正在动态生成那些选择菜单,所以每个菜单都有不同的ng-model。这是来自控制器的代码:
$scope.numberOfCoauthors = 0;
$scope.addCoauthors = function() {
$scope.index = "input_" + $scope.numberOfCoauthors;
console.log("Scope.model : " + $scope.index);
var $div = $("<p> Coautor: </p> <select ng-model='" + $scope.index + "'" +
" ng-options='user.username for user in allUsers' </select>" +
"<pre> {{ " + $scope.index + " | json }} </pre>")
var target = angular.element(document.querySelector('#coauthors'));
angular.element(target).injector().invoke(function($compile) {
var addedSelect = angular.element(target).scope();
target.append($compile($div)(addedSelect));
//$scope.$apply();
});
$scope.numberOfCoauthors++;
}
$scope.getSelectedValues = function () {
if( $scope.numberOfCoauthors > 0) {
for(i=0; i<$scope.numberOfCoauthors; i++) {
var inputName = "input_"+i;
console.log(inputName);
console.log($scope.inputName);
}
}
}
当我试图获取 $ scope.inputName 的值时,我得到了未定义的内容,所以我认为这些模型实际上没有添加到范围内,但我真的不知道如何添加它们。
答案 0 :(得分:1)
var myApp = angular.module('myApp',[]);
myApp.controller('controller', ['$scope', function($scope) {
$scope.users = [{id:1,username:"julien"},{id:2,username:"robert"}];
$scope.coAuthors = [];
$scope.coAuthor = {};
$scope.addCoauthor = function(){
$scope.coAuthors.push($scope.coAuthor);
};
$scope.coAuthorShow = false;
}]);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="controller">
<div ng-show="coAuthorShow">
<div ng-repeat="coA in coAuthors">{{coA.username}}</div>
<select name="mySelect" id="mySelect"
ng-options="user.username for user in users"
ng-model="coAuthor"></select>
<button ng-click="addCoauthor()">ADD CoAuthor</button>
</div>
<button ng-click="coAuthorShow = !coAuthorShow">Add coAuthors</button>
</div>
&#13;
你可以做类似的事情,创建选择并隐藏他