ng-model naming issue, trying to build an array but got hash instead - javascript

I'm trying to build an array with ng-model,
<div ng-repeat="n in [1, 2, 3]">
<input type="text" class="form-control" ng-model="headers[$index].key">
<input type="text" class="form-control" ng-model="headers[$index].value">
</div>
When I do angular.toJson ($scope.headers), I got:
{
"headers": {
"0": {
"key": "xxx",
"value": "yyy"
}
}
}
But I wanted this,
{
"headers": [
{
"key": "xxx",
"value": "yyy"
}
]
}
Is it impossible to get that?

Is this what you mean?
DEMO
index.js
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.2/angular.js" data-semver="1.4.2"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="object in transformedData">
<input type="text" class="form-control" ng-model="object.key">
<input type="text" class="form-control" ng-model="object.value">
</div>
<pre>{{transformedData}}</pre>
</body>
</html>
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
var data = {
"headers": {
"0": {
"key": "xxx",
"value": "yyy"
}
}
};
$scope.transformedData = transformData(data.headers)
function transformData(data){
var arr = [];
for(var key in data){
arr.push(data[key])
}
return arr;
}
});

You just need to initialize your header as an array and ng-model assignments will work.
I have altered the plunker shared by #Matt, check it here
http://plnkr.co/edit/z6Cz6R3gZpDCsXSUmIEG?p=preview

Related

AngularJS reference variables based on another variable

I want to be able to reference a variable in an Angular template that is built up on another variable with a filter.
So for example, I might have this in the controller:
$scope.EuropaLeague = true;
If I do this in the template it works as expected:
<div ng-if="EuropaLeague">
</div>
But what if I wanted to dynamically populate the ng-if with something coming from an ng-repeat e.g.
{{item.leagueName | myFilter}}
So the above would reference my scope variable $scope.EuropaLeague E.g. True or False?
Thanks
Here is working code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.leagues =
[
{
"id": 1,
"name": "ChampionsLeague",
},
{
"id": 2,
"name": "EuropaLeague",
},
{
"id": 3,
"name": "FACup",
}
]
$scope.obj = {};
$scope.obj['EuropaLeague'] = false;
$scope.obj['FACup'] = false;
$scope.obj['ChampionsLeague'] = true;
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.20/angular.js" data-semver="1.3.20"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<ul ng-repeat="item in leagues" ng-if="item.name">
<li ng-if="obj[item.name]">{{item.name}}</li>
</ul>
</body>
</html>

Form control with angular.js

I have been playing about with angular and forms but I am having some trouble with the code below. I thought that it should add forenames to the ones already displayed by the ng-repeat whenever the form is submitted but the submit button appears to do nothing.
HTML:
<!DOCTYPE html>
<html lang="en" ng-app="file">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script types=text/javascript" src="formLoops.js"></script>
<title>Title</title>
</head>
<body ng-controller="PersonalDetailsController as person">
<p ng-repeat="info in person.details">{{info.forename}}</p>
<form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="addPerson(person)">
<blockquote>
<p>{{dataCtrl.person.forename}}</p>
<p>{{dataCtrl.person.surname}}</p>
</blockquote>
<label>Forename:</label>
<input ng-model="dataCtrl.person.forename"/>
<label>Surname:</label>
<input ng-model="dataCtrl.person.surname"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
JS:
var app = angular.module("file", []);
app.controller("PersonalDetailsController", function() {
this.details = personalDetails;
});
app.controller("DataEntryController", function() {
this.person = {};
this.addPerson = function(person) {
person.personalDetails.push(this.person);
};
});
var personalDetails = [{
forename: "John",
surname: "Doe"
},
{
forename: "John",
surname: "Smith"
}
];
You need to do two changes to the code
1) In HTML you need to add the ng-submit="dataCtrl.addPerson(person)"
since you are using the controller as syntax
2) You need to change your js code as follows person.personalDetails.push(this.person); to person.details.push(this.person);
This is because your repeat is working with the details array so you need to push the new data to the details array itself. You are trying to push the data inside the global array that is why it is not worked
Thanks
since you are using the controllerAs use the controllerAs reference when you are calling the function. like ng-submit="dataCtrl.addPerson(person)"
<form name="PersonalDetailsForm" ng-controller="DataEntryController as dataCtrl" ng-submit="dataCtrl.addPerson(person)">
You will need to find a way of sharing data between controllers.
One of the ways is using an angular service.
Check out this plunk!
https://plnkr.co/edit/oimKIgCDKknwsmSWbUsT?p=preview
script.js
var app = angular.module("file", []);
app.controller("PersonalDetailsController", function(PersonService) {
this.details = PersonService.personalDetails;
});
app.controller("DataEntryController", function(PersonService) {
this.person = {};
this.addPerson = function(person) {
PersonService.personalDetails.push(this.person);
};
});
app.service("PersonService", function() {
this.personalDetails = [{
forename: "John",
surname: "Doe"
}, {
forename: "John",
surname: "Smith"
}];
});
index.html
<!DOCTYPE html>
<html lang="en" ng-app="file">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
<script types="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script types="text/javascript " src="script.js"></script>
<title>Title</title>
</head>
<body ng-controller="PersonalDetailsController as person ">
<pre>
{{person | json}}
</pre>
<p ng-repeat="info in person.details ">{{info.forename}}</p>
<form name="PersonalDetailsForm " ng-controller="DataEntryController as dataCtrl " ng-submit="dataCtrl.addPerson(dataCtrl.person) ">
<pre>
{{dataCtrl.person | json}}
</pre>
<label>Forename:</label>
<input ng-model="dataCtrl.person.forename " />
<label>Surname:</label>
<input ng-model="dataCtrl.person.surname " />
<input type="submit " value="submit " />
</form>
</body>
</html>

dynamic radio button generation in angularjs

From this json array I need to build dynamic radio buttons with mobile numbers in angularjs:
challengeSelectInfo:
[
{"mob_0" : "xxxxx1211"},
{"mob_1" : "xxxxx1211"},
{"mob_2" : "xxxxx1211"}
]
I tried ng-repeat and iterate over challengeSelectInfo but the issue that I'm facing is keys(mob_0,mob_1,mob_2) are different and I'm unable to generate dynamic radio buttons.
Any help is appreciated.
Thanks
You need to specify keys for your arrays :
$scope.newArr = [];
angular.forEach(challengeSelectInfo, function(val, key) {
/* do something for all key: value pairs */
$scope.newArr.push({id: key, value: val});
});
Then loop through newArr arrays and assign to radio button :
<input name="{{item.value}}" type="radio" ng-model="item.id" value="{{item.value}}">
made this simply for your understanding purpose hope you can achieve your requirement by using this
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.challengeSelectInfo= [
{"mob_0" : "xxxxx1211"},
{"mob_1" : "xxxxx1211"},
{"mob_2" : "xxxxx1211"} ];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="(k,v) in challengeSelectInfo ">
<div ng-repeat="(x,y) in v">
<input type="radio" />{{y}}
</div>
</div>
</body>
</html>
Can you check this JSFIDDLE Example
var data = { "challengeSelectInfo" : [ {"mob_0" : "xxxxx1211"},
{"mob_1" : "xxxxx1211"}, {"mob_2" : "xxxxx1211"} ]}
$scope.radioGrp = (data['challengeSelectInfo'] || []).map(function(obj){
for(var i in obj){
return { 'value': i, 'name': obj[i] };
}
});
<input type="radio" ng-repeat="rb in radioGrp" ng-value="rb.value" ng-modal="radioValue" name="{{rb.name}}">

Find out if there are selected more than one on Checkbox

That is how I have a checkbox and it must be such that when for example, I click on my button, so it must be like to know that there must be more than one of them. So it must have more value in total.
As it is right now gives no error or success message in my console.log ().
<input type="checkbox"
ng-checked="ItemSelected"
name="SelectedTypes"
value="2" />
<input type="checkbox"
ng-checked="ItemSelected"
name="SelectedTypes"
value="3" />
<input type="checkbox"
ng-checked="ItemSelected"
name="SelectedTypes"
value="4" />
<input type="button" class="btn btn-success" value="Næste" ng-click="UppersViewClick()" />
CreateUserInfo.js - File
$scope.UppersViewClick = function ()
{
if ($scope.ItemSelected !== undefined)
{
if ($scope.ItemSelected.length > 1) {
$scope.UppersViewInfo = false;
$scope.PantsViewInfo = true;
console.log("succes")
}
else
{
console.log("error");
}
}
}
So the purpose it is that I should be sure me that more than one or just a value out of it all.
You cannot get checked boxes like that since all refers to the same model,
$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];
DEMO
var app = angular.module('plunker', []);
app.controller('MyCtrl', function($scope) {
$scope.records = [ { "Id": 1 }, { "Id": 2 }, { "Id": 3 } ];
$scope.selected = {};
$scope.ShowSelected = function() {
$scope.records = $.grep($scope.records, function( record ) {
return $scope.selected[ record.Id ];
});
};
});
<!doctype html>
<html ng-app="plunker" >
<head>
<meta charset="utf-8">
<title>AngularJS Plunker</title>
<link href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script src="https://raw.github.com/twitter/bootstrap/master/docs/assets/js/bootstrap.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
<script src="https://raw.github.com/angular-ui/angular-ui/master/build/angular-ui.js"></script>
<script src="app.js"></script>
</head>
<body>
<div data-ng-controller="MyCtrl">
<ul>
<li data-ng-repeat="record in records">
<input type="checkbox" ng-model="selected[record.Id]"> {{record.Id}}
</li>
</ul>
Show Selected
</div>
</body>
</html>

ng-change not calling a function

my ng-table is being build like this
<table ng-table="storeCommandsTableParams" class="table tile">
<tr ng-repeat="storeCommand in $data">
<td>
<input type="checkbox" ng-change="vm.toggleCommandSelection(storeCommand)" ng-model="vm.selectedCommands" >
</td>
</tr>
</table>
and i have controller setup like this.
var vm = this;
vm.selectedCommands = { };
vm.toggleCommandSelection = function (storeCommand) {
var idx = vm.selectedCommands.indexOf(storeCommand);
// is currently selected
if (idx > -1) {
vm.selectedCommands.splice(idx, 1);
}
// is newly selected
else {
vm.selectedCommands.push(storeCommand);
}
};
what i am trying to accomplish is that when ever user clicks a check-box the respective storeCommand should be sent to a function vm.toggleCommandSelection so that i could have list of storeCommands selected. but this function is not fired.
Plunker
Your model is not storeCommand but vm.selectedCommands. So ng-change won't be triggered in this case when you click on the checkbox. May be you can use ng-click instead.
Try this
<input type="checkbox" ng-click="vm.toggleCommandSelection($event, storeCommand)">
var vm = this;
vm.selectedCommands = [];
vm.toggleCommandSelection = function ($event, storeCommand) {
var idx = vm.selectedCommands.indexOf(storeCommand);
if ($event.target.checked) {
if (idx === -1) {
vm.selectedCommands.push(storeCommand);
}
}
else {
if (idx > -1) {
vm.selectedCommands.splice(idx, 1);
}
}
};
Demo
http://plnkr.co/edit/kcW7YCWsXE8mtZoxjm1J?p=preview
Question is not cleared but i will suggest you to use $scope. Here i am supposing that all your data in controller is is $scope.data
In from end HTML:
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.3.x" src="https://code.angularjs.org/1.3.15/angular.js" data-semver="1.3.15"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<table ng-table="storeCommandsTableParams" class="table tile">
<tr ng-repeat="category in categories">
<td>
<label class="checkbox" for="{{category.id}}">
<input type="checkbox" ng-model="selection.ids[category.id]" name="group" id="{{category.id}}" / >
{{category.name}}
</td>
</tr>
<pre ng-bind="selection.ids | json"></pre>
</table>
</body>
</html>
In script in respective contrller, write:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.categories = [ { "name": "Sport", "id": "50d5ad" } , {"name": "General", "id": "678ffr" } ];
$scope.selection = {
};
});
Hi, As i understood, i have updated my answer with dummy data. Also please find the working link for plunker here PLUNKER

Categories

Resources