Creating array with ng-model when checkbox selection - angularjs

I am new to angularjs and want to create the model array when i click the checkbox and below is my code..
$scope.selectedAlbumSongs = [{
'name': 'song1',
'url': 'http://test/song1.mp3'
}, {
'name': 'song2',
'url': 'http://test/song2.mp3'
}, {
'name': 'song3',
'url': 'http://test/song3.mp3'
}];
$scope.playList = {};
HTML:
<fieldset data-role="controlgroup">
<legend>Select songs to play</legend>
<label ng-repeat="song in selectedAlbumSongs">
<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="playList[song.url]">
<label for="{{song.name}}">{{song.name}}</label>
</label>
</fieldset>
The above code updating the playList as shown below when i click the checkbox
{
"http://test/test1.mp3": true,
"http://test/test2.mp32": true,
"http://test/test3.mp3": false
}
But I want to create the ng-model in the below format, and remove the object when the checkbox is unchecked (for ex. if the uncheck the song3, the song3 object removed from the array). Can you tell me how can write this logic?
Expected:
[{
name: "song1",
url: "http://test/song1.mp3"
}, {
name: "song2",
url: "http://test/song2.mp3"
}]

You can do it like this:
$scope.selectedAlbumSongs = [ { 'name': 'song1', 'url': 'http://test/song1.mp3' }, { 'name': 'song2', 'url': 'http://test/song2.mp3' }, {'name': 'song3', 'url': 'http://test/song3.mp3' }];
$scope.selectedSongs = function () {
$scope.playList = $filter('filter')($scope.selectedAlbumSongs, {checked: true});
}
Then, simple call selectedSongs() when the selection is changed:
<input type="checkbox" name="{{song.url}}" id="{{song.name}}" ng-model="song.checked" ng-change="selectedSongs()">
See demo here

Related

ng-click not working with Datatable and Angular Js

I have read several similar questions but none worked for me on this issue. I am using laravel-datatable with angular js. But 'ng-click' does not work with the dynamically generated datatable buttons. I read about $compile but dont know how to implement it with the table. Am very new to angular js.
When I click on the button nothing happens.
app.controller('myController', ['$scope','$compile', function($scope, $compile) {
$('#stafftbl').DataTable( {
paging: true,
"ordering": true,
"searching": true,
"bInfo" : true,
deferRender: true,
ajax: 'get_staffsalary',
columns: [
{ data: 'staff_num', name: 'staff_num'},
{ data: 'staffname ', name: 'staffname' },
{ data: 'salary', name: 'salary' },
{ data: 'date_effected', name: 'date_effected' },
{ data: 'updated_at', name: 'updated_at' },
{ data: null, render: function (data, type, full) {
return '<button class="btn btn-xs btn-primary" ng-click="update('+full.id+')">Update Salary</button> ';
}},
],
});
$scope.update= function (id) {
alert(id)
}
}]);
Please any help with this?
Yes, you are correct in that you need to use $compile.
After dynamically adding html with angular attributes in it, like you are with your data table, you must call $compile so that angular can pick up the attributes.
You'll need to inject the $compile service into your controller right after $scope. Then, after the HTML has been added you will need to compile the new DOM and link it to the scope by calling $compile(new_html)($scope) in the context of your controller.
Refer to the $compile doco for reference
I solved it using #MJL 's answer. Here is the full block of code, it may hep someone else
app.controller('myCtrl', ['$scope','$compile', function($scope, $compile) {
var table = $('#stafftbl').DataTable( {
processing: false,
serverSide: false,
deferRender: true,
ajax: 'get_staffsalary',
columns: [
{ data: 'staff_num', name: 'staff_num'},
{ data: 'salary', name: 'salary' },
{ data: 'date_effected', name: 'date_effected' },
{ data: 'updated_at', name: 'updated_at' },
{ data: null, render: function (data, type, full) {
return '<button class="btn btn-xs btn-primary text-size-small" ng-click="clickme()>Update</button> ';
}},
],
"createdRow": function ( row, data, index ) {
$compile(row)($scope); //add this to compile the DOM
}
})
$scope.clickme = function () {
alert('clicked me')
}
}]);

angular dropdown multiselect to connect data between three dropdowns

I have three multiselect dropdowns:-
<label>Dropdown One</label>
<div ng-model="a.dp1" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownOne" extra-settings="multiSelectSettings">
</div>
<label>Dropdown Two</label>
<div ng-model="a.dp2" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownTwo" extra-settings="multiSelectSettings">
</div>
<label>Dropdown Three</label>
<div ng-model="a.dp3" ng-dropdown-multiselect="" options="multiSelectArray" selected-model="dropDownThree" extra-settings="multiSelectSettings">
</div>
Directive Code:-
(function () {
'use strict';
angular.module('myApp.components')
.directive('page', page);
page.$inject = ['$http', '$timeout', 'ApiServices'];
function page($http, $timeout, ApiServices) {
return {
restrict: 'EA',
scope: {},
controller: function ($scope) {
$scope.a = { };
$scope.dropDownOne = [];
$scope.dropDownTwo = [];
$scope.dropDownThree = [];
$scope.multiSelectArray = [{
name: "Ayan"
}, {
name: "Rita"
}, {
name: "Mohit"
}, {
name: "Shittal"
}, {
name: "Jayant"
}, {
name: "Sachin"
}, {
name: "Tina"
}, {
name: "Babita"
}, {
name: "Priya"
}];
$scope.multiSelectSettings = {
smartButtonMaxItems: 11,
scrollable: true,
displayProp: "name",
idProp: "name",
externalIdProp: "name"
};
},
templateUrl: 'js/folder/system/page.html'
};
}
})();
What I am trying to do here is when I select particular options from 'Dropdown One' the same options got selected in 'Dropdown Two' and 'Dropdown Three' and get disabled so that users can't unselect them. Also, the users can select more options in 'Dropdown Two' and 'Dropdown Three' if they want, but the options from 'Dropdown One' should be checked already and disabled.
I am trying to disable the options using 'disabled' attribute but not able to for selected options. Any idea how I can do that?

How to get all checked checkboxes value by ng-model in Angular?

here is the jsfiddle.
HTML:
<div ng-app="app">
<div ng-controller="ctrl">
<div ng-repeat="item in list">
<div mycb group="{{item.group}}" title="{{item.title}}" is-checked="item.isChecked" value="{{item.value}}" update="callMe()"></div>
</div>
<p>{{result}}</p>
</div>
</div>
JS:
angular.module("app",[])
.controller("ctrl", ["$scope", function($scope){
$scope.list = [
{ group: "pet", title: "dog", isChecked: true, value: "dog" },
{ group: "pet", title: "cat", isChecked: true, value: "cat" },
{ group: "pet", title: "bird", isChecked: true, value: "bird" },
{ group: "pet", title: "snake", isChecked: true, value: "snake" },
{ group: "pet", title: "boy", isChecked: true, value: "boy" },
{ group: "pet", title: "cup", isChecked: true, value: "cup" }
];
$scope.callMe = function(){
var collection = [];
for(var i=0;i<$scope.list.length;i++){
var isChecked = $scope.list[i].isChecked;
if(isChecked){
collection.push($scope.list[i].value);
}
}
$scope.result = collection.join(" ");
}
}])
.directive("mycb", function(){
return{
restrict: "A",
scope: {
title: "#",
isChecked: "=",
group: "#",
value: "#",
update: "&"
},
template: "<input type='checkbox' ng-model='isChecked' name='{{group}}' value='value' ng-change='update()'>{{title}}"
};
})
I created a group of checkbox and it will be updated when each of them is clicked.
By default, all checkboxes are checked. When I click the first one, it will be turned to status unchecked. The value of other checked boxes will show up.
For example:
dog,cat,bird,snake,boy,cup
When I click dog, the checkbox of dog will be turned to unchecked and "cat,bird,snake,boy,cup" will show up. Actually, it not happened like that. It shows "dog,cat,bird,snake,boy,cup".
Please check it out and give me a hand. Many thanks!
You can use an arrray to keep track of the boxes that are checked.
$scope.selectedCheckboxes = [];
$scope.callMe=function(item){
var idx = $scope.selectedCheckboxes.indexOf(item);
// is currently selected
if (idx > -1) {
$scope.selectedCheckboxes.splice(idx, 1);
}
// is newly selected
else {
$scope.selectedCheckboxes.push(item);
}
};
And in html pass item.value to callMe function. You wil have all the value that are checked in $scope.selectedCheckboxes
<div ng-repeat="item in list">
<div mycb group="{{item.group}}" title="{{item.title}}" is-checked="item.isChecked" value="{{item.value}}" update="callMe(item.value)"></div>
</div>
HTML
<div ng-repeat="item in list">
<div mycb group="{{item.group}}" title="{{item.title}}" is-checked="item.isChecked" value="{{item.value}}" ng-change="callMe()"></div>
</div>
Use ng-change event. Call Me function called when the user clicked on the checkbox. you can easily track all the checked checkbox in the controller.
Let me know if you need help more. Thanks.

Posting data using resource angularjs

I can Post data , with first method, but when i am using $resource POST, it doesn't work. Whats wrong with my createInventory function
$scope.addInventory = function(inventory, $location) {
$http.post("http://localhost/api/v1/inventory/", inventory)
.success(function(data) {
$scope.info.objects.key = data;
$location.path('/inventory');
});
};
And with this method it doesnt work at all
$scope.createInventory = function(){
Inventory.create($scope.info);
$location.path('/inventory/add/');
};
Here goes the template
<label>Name</label>
<input class="form-control" type="text" ng-model="inventory.name" /><br />
<label>Slug</label>
<input class="form-control" type="text" ng-model="inventory.slug" /><br />
<label>Description</label>
<input class="form-control" type="text" ng-model="inventory.description" /><br />
<label>Category</label>
<select ng-show="!show" ng-model="inventory.category" ng-options="category.name for category in category.objects">
<option value="" selected>--Please select your category--</option>
</select>
<input type="button" class="btn btn-primary" ng-click="createInventory()" value="Save" />
I have ng-repeat defined in other template
ng-repeat="inventory in info.objects"
Here if needed is my factory
app.factory('Category', function($resource, $http) {
return $resource('http://localhost/api/v1/category/:id/', {},
{
update: {
method: 'POST',
isArray: false
},
save: {
method: 'PUT'
},
query: {
method: 'GET',
isArray: false
},
create: {
method: 'POST'
},
drop: {
method: 'DELETE',
params: {id: '#id'}
}
}
);
});
Entire controller
app.controller('InventoryCtrl', function($scope, $http, Inventory, Category, $location) {
$scope.createInventory = function(){
Inventory.create($scope.info);
$location.path('/inventory/add/');
};
$scope.info = Inventory.query();
$scope.category = Category.query();
$scope.addInventory = function(inventory, $location) {
$http.post("http://api.bos.lv/api/v1/inventory/", inventory)
.success(function(data) {
$scope.info.objects.key = data;
});
};
});
my api
{
meta: {
limit: 20,
next: null,
offset: 0,
previous: null,
total_count: 2
},
objects: [
{
category: {},
count: 1,
created: "2014-02-27T16:23:40.813690",
description: "asd",
id: 50,
location: "asd",
name: "asd",
resource_uri: "/api/v1/inventory/50",
slug: "asd",
status: "Broken"
},
{
category: {},
count: 1,
created: "2014-02-27T16:46:05.017178",
description: "asd",
id: 51,
location: "sad",
name: "bubu",
resource_uri: "/api/v1/inventory/51",
slug: "bubu",
status: "Broken"
}
]
}
I'm guessing you need to wait for the post to finish before you can move to another location... so you need to change the path on the callback.
$scope.createInventory = function(){
Inventory.create($scope.info, function(param) {
$location.path('/inventory/add/');
);
};

Set ng-model to value value in scope?

I'm working on a simple angular app with two controllers:
function Invite($scope) {
$scope.fieldsets =
[
{
fields:
[
{
label: 'First Name',
name: 'firstname',
key: 'entry.810220554',
type: 'text',
required: true
},
{
label: 'Last Name',
name: 'lastname',
key: 'entry.1653030831',
required: true,
},
{
label: 'Email',
name: 'email',
key: 'entry.1727688842',
required: true,
type: 'email',
},
{
key: 'entry.1602323871',
type: 'radio',
labels:
[
{
name: 'media',
label: 'Media'
},
{
name: 'frilans',
label: 'Frilans'
}
],
}
],
}
];
}
function Questionnaire($scope, $http){
$scope.post = function(){
console.log();
$http.post('/signup.php', $scope.quiz).
success(function(data, status, headers, config){
console.log(data);
});
};
}
The Questionare-scope is a child of the invite scope. Here is simplified version of the layout
<div ng-controller="Invite">
<form ng-controller="Questionnaire" method="POST" ng-submit="post()">
<input ng-model="{{field.key}}" />
</form>
</div>
The first one generates a form where I want the key-values to be used as ng-model.
In the second scope, so that I can post them to the server with that key.
I first tried to use
<input ng-model="{{field.key}}" />
in my html template, this was my intuitive guess, but it rendered an error.
<input ng-model="field.key" />
this also giving error.
Here is a plnkr:
http://plnkr.co/edit/rnQXlCCFQypVLs20OuTt?p=preview
There is no object fields in the questionnaire scope. You may be able to reference the object to in the outer scope by using ng-repeat=field in $parent.fields, I'm not sure if nested scopes are related via prototypical inheritance.
Another approach would be to create a service that tracks fields and inject it into all the controllers that need access to the data.

Resources