Dynamic ng-model in ng-repeat - javascript

Using Angular JS, I have this object
var pages = [
{ name: 'users', title : "Users" },
{ name: 'roles', title : 'Roles' }
];
I'm trying to create a page for user roles. For that I need 4 checkboxes for each page. Each page must have 4 rules. Access, show, edit, delete.
Displaying pages in a ng-repeat
<div ng-controller='PageCtrl'>
<ul>
<li ng-repeat='page in pages'>
{{ page.title }}
<input type="checkbox" name="access"> Access
<input type="checkbox" name="show"> Show
<input type="checkbox" name="edit"> Edit
<input type="checkbox" name="delete"> Delete
</li>
</ul>
</div>
So I need to pass those checkboxes values to the $scope. How can I bind a model for each checkbox?
Like this
<input type="checkbox" name="access" ng-model='page.name+_access'> Access
Checkbox model name should start with page.name. Like users_access, users_show...

You can use the following syntax:
ng-model="page[page.name+'_access']"
But as a matter of fact, it looks one can move those groups into controller as well, then use another ng-repeat. Like this:
HTML:
<div ng-controller="PageCtrl">
<ul>
<li ng-repeat='page in pages'>{{ page.title }}
<label ng-repeat="right in rights">
<input type="checkbox" ng-model="page[page.name + '_' + right]" name="{{right}}" />{{right|capitalize}}</label>
<button ng-click="log(page)">Log</button>
</li>
</ul>
</div>
JS:
var module = angular.module('myAp', [])
.controller('PageCtrl', ['$scope', function ($scope) {
$scope.pages = [{
name: 'users',
title: "Users"
}, {
name: 'roles',
title: 'Roles'
}];
$scope.rights = ['access', 'show', 'edit', 'delete'];
$scope.log = function (page) {
console.log(page);
}
}]).filter('capitalize', function() {
return function (value) {
return value.charAt(0).toUpperCase() + value.slice(1);
};
});
Demo.

Related

Angularjs: input for ng-repeat elements

Sorry for my language skills, hope you understand all.
I need to make inputs for ng-repeat elements, to pass input data to http post.
For example: i have 4 elements, for all elements i make inputs, and f.e:
elem1- input: 1
elem2- input: 4
elem3- input: 1
elem4- input: 2
Here is my code:
.panel-body.note-link ng-repeat=("meal in mealsList track by $index")
a data-toggle="tab"
h4.pull-right.text-muted
| {{meal.price}} zł
h4.text-success
i.fa.fa-close.text-danger<> ng-click="removeMeal($index)" style="cursor: pointer;font-size: 15px;"
| {{meal.name}} {{$index}}
input.form-control type="number" ng-model="example"
| {{example}}
And i dont know, how to pass input data to controller.
Any tips,tricks?
angular.module('yourModule').controller('viewController', function($scope) {
$scope.mealList = [...];
$scope.example; //The input data will automatically bind to this variable.
});
If you want the input to change data within your meal object, then do this:
input.form-control type="number" ng-model="meal.example"
And then the property value of the meal object would bind to the input
Repeat through your mealList array and add the inputs.
Example: https://jsfiddle.net/ptzhL0uL/
Controller
function Controller1($scope) {
var vm = this;
vm.items_saved = false;
vm.mealList = [{
price: '2.99',
name: 'Pizza'
}, {
price: '1.99',
name: 'Chips'
}, {
price: '4.99',
name: 'Beer'
}];
vm.addNewItem = addNewItem;
vm.saveItems = saveItems;
function addNewItem() {
vm.mealList.push({});
}
function saveItems() {
vm.items_saved = true;
}
}
HTML
<button ng-click="ctrl.addNewItem()" class="btn btn-default">Add Item</button>
<div ng-repeat="item in ctrl.mealList">
<input type="text" ng-model="item.name">
<input type="text" ng-model="item.price">
<input type="number" ng-model="item.quantity">
</div>
<button ng-click="ctrl.saveItems()" class="btn btn-primary">Save</button>
<hr>
<div ng-if="ctrl.items_saved">
<h4>Here is your meal list:</h4>
<ul>
<li ng-repeat="item in ctrl.mealList">{{item.quantity}}{{item.name}} at ${{item.price}} each</li>
</ul>
</div>
Just attach it to the ngModel directive.
<div ng-repeat="item in array">
{{ item.output }}
<input ng-model="item.output" />
</div>

Can't execute selectall on checkboxes with Angular

I can't seem to figure out how to have another checkbox that selects all and deselects all boxes.
JSFIDDLE
<div ng-controller="tempCtrl">
<input type="checkbox" ng-model="selectAllOptions" ng-click="selectAll()" /> Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
</div>
var myApp = angular.module('myApp', []);
myApp.controller("tempCtrl", function ($scope) {
$scope.form = {
selectedTeams: {}
};
$scope.parameters = {
myMainOptions: {
teams: ['angels', 'giants', 'orioles', 'bluejays', 'athletics']
}
};
$scope.selectAll = function() {
//This is where I'm stuck
}
});
Here's a working plunkr of a simple select/deselect all checkbox:
plunkr
Controller
$scope.checkboxes = [
{
selected: false
},
{
selected: false
},
{
selected: false
}
];
// Check/uncheck all boxes
$scope.checkAll = function () {
angular.forEach($scope.checkboxes, function (obj) {
obj.selected = $scope.selectAll;
});
};
View
<p>Check all</p>
<input type="checkbox" ng-model="selectAll" ng-click="checkAll()" />
<br />
<p>Checkboxes</p>
<div ng-repeat="checkbox in checkboxes track by $index">
<input type="checkbox" ng-model="checkbox.selected" />
<label ng-show="checkbox.selected">Checkbox {{ $index+1 }} selected!</label>
</div>
First, you should make teams an array of objects like this
Controller:
$scope.parameters = {
myMainOptions: {
teams: [{name: 'angels'}, {name: 'giants'}, {name: 'orioles'}, {name:'bluejays'}, {name: 'athletics'}]
}
};
This is a better approach because, now, you can add a selected attribute to each team object.
Then you should set ng-model for each team checkbox to something like team.selected like this:
View:
<li ng-repeat="team in parameters.myMainOptions.teams">
<input ng-model="team.selected" type="checkbox" />
{{team}}
</li>
Now, if you check the angels checkbox, the object will change to {name: 'angels', selected: true}
Then your selectAll function will look like this:
Controller:
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (team) {
team.selected = $scope.selectAllOptions;
});
};
You could do forEach on $scope.parameters.myMainOptions.teams array and then set $scope.form.selectedTeams value in the loop. Also use ng-change instead of ng-click.
Markup
<input type="checkbox" ng-model="selectAllOptions" ng-change="selectAll()" />Select/Deselect All
<li ng-repeat="t in parameters.myMainOptions.teams">
<input ng-model="form.selectedTeams[t]" type="checkbox" />{{t}}</li>
<button class="btn btn-sm" type="submit" ng-click="submit(form)">SUBMIT</button> <pre>
{{form.selectedTeams}}
</pre>
Code
$scope.selectAll = function () {
angular.forEach($scope.parameters.myMainOptions.teams, function (value, index) {
$scope.form.selectedTeams[value] = $scope.selectAllOptions; //setting selectAll variable value
})
}
Working Fiddle

how to create object while using ng-repeat and array in angularjs

Hello Everyone I have face a problem to create a object with ng-repeat. when i declare the Object then the same value in filled in the text box which has same ng-model value. if i am not Declare the object then duplicacy is not occures.
If i am declare the $scope.user = {}; in js file then problem is occures. please check this. Give me a solution ASAP.
My Fiddle Link Please Check This http://jsfiddle.net/Ladjkp5s/1/
Here is my Html file
<div ng-app="myApp">
<div ng-controller='MainController' ng-init="start = 0; end = 5;">
Start: <input ng-model="start"> End: <input ng-model="end">
<ul>
<li ng-repeat="item in items | slice:start:end">{{item + 1}}
<div>
Name: <input type="text" ng-model="user.name"><br>
Address: <input type="text" ng-model="user.add"><br>
Phone: <input type="text" ng-model="user.phn"><br>
ZipCode: <input type="text" ng-model="user.zip">
</div>
</li>
</ul>
</div>
</div>
Here is my JS File
var app = angular.module('myApp', []);
app.filter('slice', function() {
return function(arr, start, end) {
return arr.slice(start, end);
};
});
app.controller('MainController', function($scope) {
$scope.items = [];
$scope.user ={};
for (var i = 0; i < 5; i++) $scope.items.push(i);
});
Thanks.
The problem is that you are using same ng-model for every item.(user.fieldName) you have to use item.fieldName.
<div ng-app="myApp">
<div ng-controller='MainController' ng-init="start = 0; end = 5;">
Start: <input ng-model="start"> End: <input ng-model="end">
<ul>
<li ng-repeat="item in items | slice:start:end">{{item.index + 1}}
<div>
Name: <input type="text" ng-model="item.name"><br>
Address: <input type="text" ng-model="item.add"><br>
Phone: <input type="text" ng-model="item.phn"><br>
ZipCode: <input type="text" ng-model="item.zip">
</div>
</li>
</ul>
</div>
</div>
http://jsfiddle.net/3akwk7tv/
Yuu can not loop in controller function, but u can create controller that loops in html like in this example
<ul>
<li ng-repeat="theItem in myData.items">{{theItem.text}}</li>
</ul>
<script>
angular.module("myapp", [])
.controller("MyController", function($scope) {
$scope.myData = {};
$scope.myData.items = [ {text : "one"}, {text : "two"}, {text : "three"} ];
});
</script>

Remove item from the list if checked

I have a list of items with a checkbox, and i have delete button. The delete only works if the item in the list is checked.
So for example i have
$scope.list = [{
name:'Groceries',
check: false
}, {
name:'Laundry',
check:false
},
{
name:'Cleaning',
check:false
}];
and in my HTML
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check"/>
<span>{{values.name}}</span>
</li>
</ul>
<button>Delete</button>
This is just the snippet of the code i have the controller declared and bootstrapped with ng-app
You should use Angular native directive ng-checked
<input type="checkbox" ng-checked="values.check"/>
You can use a filter for this:
HTML
<body ng-app="app" ng-controller='Ctrl'>
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check"/>
<span>{{values.name}}</span>
</li>
</ul>
<button ng-click="remove((list | filter:{check:true}))">Delete</button>
</body>
Controller
$scope.remove = function(items) {
alert('removing ' + items.length + ' items');
$scope.list = $filter('filter')($scope.list, { check: false});
}
Demo Plunker
<body ng-controller="MyController">
<ul>
<li ng-repeat="values in list">
<input type="checkbox" ng-model="values.check" />
<span>{{values.name}}</span>
</li>
</ul>
<button ng-click="deleteItems()">Delete</button>
</body>
controller:
myApp.controller('MyController', function($scope, $filter) {
$scope.list = [ {
name : 'Groceries',
check : false
}, {
name : 'Laundry',
check : false
}, {
name : 'Cleaning',
check : false
} ];
$scope.deleteItems = function() {
$scope.list = $filter('filter')($scope.list, {check : false})
}
})

Angular $scope.var undefined in the controller but present in HTML

This seems to be a newb question...
I have simple app that displays 2 lists of todos and one text input field for adding new todos in each list.
Problem 1: When trying to add a new todo the $scope.todoText is undefined in the controller.
Problem 2: how to add the new todo item to the correct list?
Code: JS
function TodoCtrl($scope) {
$scope.lists = [
{name:'list1',
todos:[
{text:'learn angular', done:true},
{text:'build an angular app', done:false}
]},
{name:'list2',
todos:[
{text:'buy milk', done:false},
{text:'buy fruit', done:false}]}
];
$scope.addTodo = function(listName) {
alert($scope.todoText); // Trying to fix this
// TODO add new todo to listName
$scope.todoText = '';
};
}
HTML
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
<ul>
<li ng-repeat="oneList in lists">
<ul>
<hr/>
<h2>=== {{oneList.name}} ===</h2>
<form ng-submit="addTodo({{oneList.name}})">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input type="submit" value="add">
</form>
<li ng-repeat="todo in oneList.todos">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</li>
</ul>
</li>
</ul>
</div>
</div>
JSFiddle here: http://jsfiddle.net/supercobra/v8hxg/
The model variable todoText is within the scope of the ng-repeat and the method to add it in parent scope, so you cannot access it. You can pass the collection and the new item into the add method to perform addition of a new TODO something like this
$scope.addTodo = function(list,todoText) {
list.todos.push({text:todoText,done:false});
};
I have updated your fiddle with the fixes.
http://jsfiddle.net/cmyworld/ADJn7/2/
Problem 1: You are trying to use todoText before even initializing it. Declare it before the alert:
$scope.addTodo = function(listName) {
$scope.todoText = '';
alert($scope.todoText);
};
Problem 2: To add a new ToDo to the correct list you can simply pass the index and the new Todo from the HTML:
<form ng-submit="addTodo($index, todoText)">
JS
$scope.addTodo = function(idx, todo) {
$scope.lists[idx]['todos'].push(
{text:todo, done:false}
);
};
Return the list and the text, as Chandermai explained, because of the scope:
<form ng-submit="addTodo(oneList, todoText)">
<input type="text" ng-model="todoText" size="30"
placeholder="add new todo here">
<input type="submit" value="add">
</form>
Then access it as an object in your controller:
sc.addTodo = function(listName, todoText) {
console.log(listName.name);
console.log(todoText);
// TODO add new todo to listName
};

Categories