Reputation: 359
I have this form where a user can upload an article and he has the option of adding some coauthors. If he wants to add a coauthor he would click on a button which will dynamically generate a drop down menu containing a list of other users.
The problems is that I am dynamically generating those select menus, so each of them will have a different ng-model.Here is the code from the controller:
$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);
}
}
}
When I am trying to get the value of $scope.inputName I get undefined, so I think those models are not actually added to the scope, but I don't really know how to add them.
Upvotes: 1
Views: 1146
Reputation: 106
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;
}]);
<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>
You can do something like that, create the select and hide him
Upvotes: 1