AngularJS - Using ng-repeat twice under the same controller - angularjs

I have the following DIV:
<div ng-controller="userControl">
<div ng-repeat="user in users">
<u>{{user.id}} : {{user.name}}</u><br />
<div ng-repeat="role in user.roles">
{{role.name}}
</div>
<br />
</div>
<form ng-submit="addRoleToUser()">
<select name="userSelect">
<div ng-repeat="user in users">
<option value="{{user.id}}">{{user.name}}</option>
</div>
</select>
<input type="submit" value="add">
</form>
</div>
This is my controller:
function userControl($scope,$http) {
$scope.users = [
{"id":"0","name":"Username1","roles":[{}]},
{"id":"1","name":"Username2","roles":[{}]},
]
$scope.addUser = function() {
var nextid = $scope.getNextId();
$scope.users.push({id:nextid,name:$scope.userName});
/*
$.post({}); //Push changes to server
*/
$scope.userName = '';
};
$scope.getNextId = function() {
var count = 0;
angular.forEach($scope.users, function(data) {
count = data.id;
});
var count2 = parseInt(count)+1;
return count2;
};
}
I can see the first ng-repeat is working fine and is listing the user.id and user.name, however the second ng-repeat (the one inside the form) does not display the information, is that related to the fact that I've already looped through that element in the previous div?

You misused the select directive :
<select ng-model="selectedUser" name="userSelect" ng-options="user.id as user.name for user in users">
http://docs.angularjs.org/api/ng.directive:select

Related

Angularjs ng-change and ng-repeat not properly working

In ng-change the selected value is not setting up in the ngchange function.
First time when I select a value its setting up as null, and again I try to select an another value, its setting the value of the previous selected value.
var ngInitParams = JsonConvert.SerializeObject(Model);
var firstVarId= Model.Variants.First().ProductId;
var firstVarName= Model.Variants.First().Name;
<section id="#inPageNavigationID" ng-controller="prodSpecsCtrl as main"
ng-init="main.init('#firstVarId', '#firstVarName')">
<div class="container" ng-init="main.loadSelect('#ngInitParams')">
<div>
<div class="row">
<div class="col-sm-6 fieldset">
<div class="form__item ">
<div>
<select class="-dropdown--two-columns" name="productvariants" id="sel1" data-placeholder="#selectOptionVal" ng-model="variant.ProductId"
ng-change="main.load('{{variant.ProductId}}','{{(main.JsonVariants.Variants | filter: {ProductId:variant.ProductId})[0].Name}}')">
<option value="" disabled>Select Model</option>
<option ng-repeat="variant in main.JsonVariants.Variants" value="{{variant.ProductId}}" selected="#firstVariantId" data-option-header="{{variant.CatalogCode}}">{{variant.Name}}</option>
</select>
<span class="fa fa-angle-down"></span>
</div>
</div>
</div>
</div>
</div>
<section>
this.init = function (varId, varName) {
this.load(varId, varName);
}
this.loadSelect = function (strjson) {
self.JsonVariants = JSON.parse(strjson);
}
Here is an example of an ng-change within a select.
https://plnkr.co/edit/ZhJbVfPRCLoeFwYoi3Mp?p=preview
<body ng-controller="MainCtrl">
<select ng-model="item" ng-change="changed(item)" ng-options="item.Name for item in items"></select>
<p>ID:{{selected.ID}} Name: {{selected.Name}}</p>
<p>You Selected: {{selected}}</p>
</body>
And Controller:
app.controller('MainCtrl', function($scope) {
$scope.items = [];
$scope.selected = {};
$scope.changed = function(item) {
$scope.selected = item;
}
function setupItems() {
for (var i = 0; i < 10; i++) {
var item = {ID: i, Name: "Item " + i}
$scope.items.push(item);
}
}
setupItems();
});

How to get selected option value from dropdown using angular

I have two drop downs with add resource button, when I click add resource button I need to pass selected option values from drop downs into insertResource method.How to get selected option value??I know we can easily do it using option:selected in jquery But I want do it in angular.Any help?
<body ng-app="intranet_App" ng-controller="myCtrl" ng-init="init()">
<div class="container">
<div class="row">
<div>
<label class="displayBlock margin">Project Name</label>
<input type="text" name="name" class="currentProjectName">
</div>
<div>
<label class="displayBlock margin">Resource Name</label>
<select name="ResourceInsert" id="allocateResource"><option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option></select>
</div>
<div>
<label class="displayBlock margin">Role Name</label>
<select name="ResourceInsert" id="allocateRole"><option data-ng-repeat="data in roleList" value="{{data.RoleId}}">{{data.RoleName}}</option></select>
</div>
</div>
<div class="row">
<button class="btn btn-primary addResource" ng-click="insertResource()">Add Resource</button>
</div>
</div>
</body>
<script>
var app = angular
.module('intranet_App', [])
.controller('myCtrl', function ($scope,$http) {
$scope.init = function () {
$scope.getProjId();
$scope.ResourceJson();
$scope.RoleJson();
}
$scope.getProjId = function () {
var url = document.URL;
var id = decodeURI(/id=([^&]+)/.exec(url)[1]);
var projectName = decodeURI(/val=([^&]+)/.exec(url)[1]);
$('.currentProjectName').val(projectName)
}
$scope.ResourceJson = function () {
$http.post('/Project/empList').then(function (response) {
$scope.resourceList = response.data;
console.log($scope.resourceList)
})
}
$scope.RoleJson = function () {
$http.post('/Project/roleList').then(function (response) {
$scope.roleList = response.data;
console.log($scope.roleList)
})
}
$scope.insertResource = function () {
}
});
</script>
If your questions is getting data of selected item of select. It is done as follows using ng-model directive:
<select name="ResourceInsert" id="allocateResource" ng-model="selectedValue">
<option data-ng-repeat="data in resourceList" value="{{data.EmpId}}">{{data.ResourceName}}</option>
</select>
In Controller:
console.log($scope.selectedValue, "selected Value"); //Your selected value which is EmpId.

Get the value of dynamic check boxes in angular js when submitting the form

In my HTML form there are 5 check boxes. How can I check which check boxes are checked or not at the time of the form submission?
I am using this little piece of code. Feel free to take it.
In your controller:
$scope.sentinel = [];
$scope.toggleSelection = function(value) {
// Bit trick, equivalent to "contains"
if (~$scope.sentinel.indexOf(value)) {
var idx = $scope.sentinel.indexOf(value);
$scope.sentinel.splice(idx, 1);
return;
}
$scope.sentinel.push(value);
};
Then in your HTML:
<span ng-repeat="key in $scope.yourarray">
<md-checkbox style="margin-left:30px;" aria-label="Select item"
ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox>
<br/>
</span>
This allows you to have an array of any size and using the sentinel array to register already checked values. If you check again a box, the toogleSelection will prevent you from adding again a value.
You can use the Checklist-model of Angular.js. It is very useful:
var app = angular.module("app", ["checklist-model"]);
app.controller('Ctrl1', function($scope) {
$scope.roles = [
'guest',
'user',
'customer',
'admin'
];
$scope.user = {
roles: ['user']
};
$scope.checkAll = function() {
$scope.user.roles = angular.copy($scope.roles);
};
$scope.uncheckAll = function() {
$scope.user.roles = [];
};
$scope.checkFirst = function() {
$scope.user.roles.splice(0, $scope.user.roles.length);
$scope.user.roles.push('guest');
};
$scope.showCheckedOnes = function() {
var checkedBoxes = "";
for (var i = 0; i < $scope.user.roles.length; i++) {
checkedBoxes += $scope.user.roles[i] + " ";
}
alert(checkedBoxes);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script>
<div ng-app="app">
<div ng-controller="Ctrl1">
<label ng-repeat="role in roles">
<input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}}
</label>
<div>
<div>
<button ng-click="checkAll()" style="margin-right: 10px">Check all</button>
<button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button>
<button ng-click="checkFirst()" style="margin-right: 10px">Check first</button>
<button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>
You can define the array value and map to html.
$scope.checkbox = [];
HTML
<input ng-model="checkbox[0] type="checkbox" />
<input ng-model="checkbox[1] type="checkbox" />
<input ng-model="checkbox[2] type="checkbox" />
<input ng-model="checkbox[4] type="checkbox" />
Or you can define checkbox as object and change checkbox[index] to checkbox[name].

make a list of infos adding Id in angularjs

I want to make list of infos inputing Name, Work. THere is a form with those inputs. Putting Name and Work when SAVE button clicked, it will add to the list. and view them. But I also want to add id every time. How can I do this?
here is my plunker: https://plnkr.co/edit/VDYYrxk8Bz5KIoI0HFV4?p=preview
HTML:
<body ng-controller='MyController'>
<!-- <button ng-click='toggleForm()'>Upload</button> -->
<div>
<table class='table'>
<tr>
<th>Title</th>
<th>Work</th>
</tr>
<tr ng-repeat='info in infos'>
<td>{{info.name}}</td>
<td>{{info.work}}</td>
</tr>
</table>
</div>
<form class='form'>
<div class='form-group'>
<label>Name</label>
<input class='form-control' type="text" ng-model='info.name'>
</div>
<div class='form-group'>
<label>Work</label>
<input class='form-control' type="text" ng-model='info.work'>
</div>
<div class='form-group'>
<button class='btn btn-primary' ng-click='addInfos()'>Save</button>
</div>
</form>
</body>
script::
angular
.module('app')
.controller('MyController', function($scope){
// $scope.displayForm = false;
// $scope.toggleForm = function(){
// $scope.displayForm = !$scope.displayForm;
// };
$scope.infos = [];
// var currIndex = 0;
$scope.addInfos = function () {
$scope.infos.push({
name: '',
work: ''
// id: currIndex++
});
// $scope.infos.push(obj.info);
};
})
$scope.addInfos = function () {
$scope.infos.push({
name: $scope.info.name,
work: $scope.info.work,
id: $scope.infos.length + 1 // assuming you want ids to start with 1
});
$scope.info = {}; // to clear the form fields once an input is pushed to the array
};

how can we get the array id of selected checkbox in angularjs?

I am trying to get the array id of selected checkbox but unable to get the array. I need the array in format of ["302740", "42006", "331497"]
here it is my app.js
var app = angular.module('app', []);
function Ctrl($scope) {
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
$scope.brandlist = [];
$scope.get = function (val) {
console.log(val);
var idx = $scope.brandlist.indexOf(val);
if (idx > -1)
$scope.brandlist.splice(idx, 1);
else
$scope.brandlist.push(val);
console.log($scope.brandlist);
// should come like selected array ["302740", "42006", "331497"]
}
}
and here it is the html
<div ng-controller="Ctrl">
<span ng-repeat="(key,val) in categories">
<label class="checkbox" for="{{key.tid}}">
<input type="checkbox" ng-change="get(val.tid)" ng-model="brandlist[val.tid]" ng-checked="brandlist.indexOf(val.tid) > -1" name="group" id="{{val.tid}}" />
{{val.name}}
</label>
</span>
</div>
plunker
Consider trying this
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
$scope.selecetedCategories = function toggleSelection(category){
var idx = $scope.selectedCategories.indexOf(category);
if(idx > -1){
$scope.selecetedCategories.splice(idx,1);
}
else{
$scope.selecetedCategories.push(category);
}
};
You can print the selected categories like this
console.log($scope.selecetedCategorie);
And your html:
<input type="checkbox" name="selectedCategories"
value="{{category}}" ng-checked="selectedCategories.indexOf(category) >
-1" ng-click="toggleSelection(category)"/>
If you're not worried about manipulating the source array, you can use that to maintain the state.
HTML
<div ng-controller="Ctrl">
<span ng-repeat="(key,val) in categories">
<label class="checkbox" for="{{key.tid}}">
<input type="checkbox" ng-model="val.checked" name="group" id="{{val.tid}}" />
{{val.name}}
</label>
</span>
</div>
JS:
$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
// get the selected categories
var selectedCategories = $scope.categories.filter(function(itm) {
return itm.checked;
});

Resources