AngularJS Add Multiple Objects to Object Literal - javascript

When I click "Evan" I get:
{"id":1,"name":"Evan"}
When I click "Robert" I get:
{"id":2,"name":"Robert"}
How can I modify this code to follow the above steps and get an object like this (not an array):
{"id":1,"name":"Evan"},
{"id":2,"name":"Robert"}
Here's my Plunker:
http://plnkr.co/edit/EkKlx7cJG8L0IkRTY6dU?p=preview
Here's my view:
<body ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items" ng-click="select(item)">
{{item.name}}
</li>
</ul>
<p ng-show="selected">{{selected}}</p>
</body>
Here's my controller:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = {
"1": {
"id": 1,
"name": "Evan"
},
"2": {
"id": 2,
"name": "Robert"
},
"3": {
"id": 3,
"name": "Justin"
}
}
$scope.selected = {};
$scope.select = function (item) {
$scope.selected = item;
}
});

You need to supply a key for the intended value inside your selected object.
If you're opposed to an array, I'd suggest you modify the select function as such:
$scope.select = function (item) {
$scope.selected[item.id] = item;
};
plunker

Related

Having Uncaught Error: [$rootScope:infdig] while filtering nested ng-repeats

I am trying to filter nested ng-repeats while using a custom filter recommended by official angularjs error helper.
On my local machine, it didn't filter anything as well as throw an error in console:
Error: $rootScope:infdig
Infinite $digest Loop
I have attached a plunker demo of this issue.
In plunker, the filtering is working fine but still the error is appearing in console.
HTML:
<body ng-app="myApp">
<h1>Hello Vehicles!</h1>
<div ng-controller="myCtrl">
<input type="text" class="filter-vehicles-input" id="filter_vehicles" name="filter_vehicles" value="" placeholder="Search Vehicles" ng-model="filter_vehicles">
<ul>
<li ng-repeat="(key, vModel) in vehiclesByModel | customFilter: filter_vehicles">
<div>
<input type="checkbox" name="model_id" value="{{key}}" ng-click="selectAllTrucks($event)">
<strong>{{ key | uppercase }}</strong>
</div>
<ul>
<li ng-repeat="vehicle in vModel track by $index">
<input type="checkbox" name="vehicle_id" value="{{vehicle.TruckID}}" ng-model="selectedVehicleIds[vehicle.TruckID]"> {{ vehicle.licensePlate + ' (' +vehicle.identifier+ ')' | uppercase }}
</li>
</ul>
</li>
</ul>
</div>
</body>
JS:
angular.module('myApp', [])
.controller('myCtrl', function($scope) {
$scope.vehiclesByModel = {
"Toyota": [{
"vehicleID": "102",
"licensePlate": "XYZ123",
"identifier": "Corolla"
}, {
"vehicleID": "103",
"licensePlate": "XYZ124",
"identifier": "Corolla Advanced"
}],
"Honda": [{
"vehicleID": "104",
"licensePlate": "XYZ1254",
"identifier": "City"
}, {
"vehicleID": "105",
"licensePlate": "XYZ124ghf",
"identifier": "Civic"
}]
};
}).filter('customFilter', function() {
return function(input, search) {
if (!input) return input;
if (!search) return input;
var expected = ('' + search).toLowerCase();
var result = {};
angular.forEach(input, function(value, key) {
result[key] = {};
angular.forEach(value, function(v, k) {
var actual = ('' + v.identifier).toLowerCase();
var actual2 = ('' + v.licensePlate).toLowerCase();
if (actual.indexOf(expected) !== -1 || actual2.indexOf(expected) !== -1) {
result[key][k] = v;
}
});
});
return result;
};
});
Demo: http://plnkr.co/edit/b0oghi75e5S0W8pnmAW8?p=preview

Ng-repeat datas from 2 json Angular

I try to get data from 2 jsons and list it in table :
1st 'names.json':
[
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
]
Second 'data.json'
[
{
"data": "25-12-2014"
}
]
Javascript:
app.service('service', function($http, $q){
this.getNames = function () {
var datas = $http.get('data,json', { cache: false});
var names = $http.get('names.json', { cache: false});
return $q.all([datas, names]);
};
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.names.data;
$scope.datas = data.datas.data;
});
Now i must show it in table HTML :
div ng-controller="FirstCtrl"
<table>
<tbody>
<tr ng-repeat="name in names.concat(datas)">
<td>{{name.name}}</td>
<td>{{name.data}}</td>
</tr>
</tbody>
</table>
</div>
I try concat() but it dont work, is there any method to show in table datas from 2 arrays by ng-repeat?
Thanks for answers in advance!

AngularJS : How to watch a service object

I have tried using different examples with the watch function, but I am not able to make it work. I am watching a service that contains a array of objects, each object contains a array of arrays. I need to watch the array of arrays for changes.
JSON
[{
"name": "Chantal Hamlet - Green Castle Homes",
"subId": "10223",
"bldId": "13551",
"data": [
[179900, 1386],
[214900, 1440],
[194500, 1496],
[217900, 1504],
[189900, 1542],
[184900, 1546],
[192500, 1570],
[189900, 1576],
[191900, 1598],
[204900, 1626],
[219900, 1651],
[212900, 1704],
[214900, 1787],
[219900, 1837],
[224900, 1857]
]
}, {
"name": "Ella Sea Condos - Sahnow Construction",
"subId": "9761",
"bldId": "27380",
"data": [
[199900, 1500]
]
}]
Watch function
$scope.$watchCollection(function () {
return chartService.series
},
function (rawData) {
$scope.seriesData = rawData;
});
Service
chart.factory('chartService', function () {
return {
getSeries: function () {
return this.series;
},
setSeries: function (series) {
this.series = series;
},
The problem is that your setSeries function is changing the object that's being watched.
Think of it like
chartService.series = ObjectA
Watch ObjectA
chartService.series = ObjectB
ObjectA has not changed.
To fix this you need to wrap it in a larger object that doesn't change.
angular.module('chartModule', [])
.controller("chartController", ['$scope', 'chartService',
function($scope, chartService) {
$scope.seriesData = chartService.seriesContainer;
$scope.changeData = function() {
chartService.seriesContainer.series = [{
"name": "New Name",
}];
}
}
]).factory('chartService', function() {
return {
getSeries: function() {
return this.series;
},
setSeries: function(series) {
this.series = series;
},
seriesContainer: {
series: [{
"name": "Chantal Hamlet - Green Castle Homes",
}]
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="chartModule">
<div ng-controller="chartController">
{{seriesData.series[0].name}}
<button ng-click="changeData()">Change Data</button>
</div>
</body>
If you use a wrapper you actually don't even need a watch, it will happen automatically

How to return and array inside a JSON object in Angular.js

Imagine the following JSON API:
[
{
"id": "1",
"name": "Super Cateogry",
"products": [
{
"id": "20",
"name": "Teste Product 1"
},
{
"id": "21",
"name": "Teste Product 2"
},
{
"id": "22",
"name": "Teste Product 3"
}
]
}
]
Is there anyway for me to only return the products array with Angularjs?
I have a simple service calling the JSON:
services.factory("ProductService", function($http) {
return {
"getProducts": function() {
return $http.get("/product/index");
}
};
});
That is being called in the controller like so:
components.success(function(data) {
$scope.products = data;
});
But it returns the whole JSON as expected, I need it to return only the "products" array so I can iterate through it.
PS: This is merely a simple example to illustrate the problem, I realize that I could change the API to fit my needs in this case, but that's not the point.
You would just assign the products array to your scope property...
components.success(function(data) {
$scope.products = data[0].products;
});
You could customize it via a promise, and do it yourself.
"getProducts": function() {
var promise = $q.defer();
$http.get("/product/index").success(function(data){
promise.resolve(data && data.products);
}).error(function(msg){
promise.reject(msg);
})
return promise.promise;
}
How to use:
getProducts().then(
function(data) {
$scope.products = data;
},
function(msg){
alert('error')
}
);

How to get the menu key from the json in angularjs

I want the get the "menu1" or "menu2" fields and so on, how to do it in angularjs?
the json is following:
{
"menu1": [
{
"item": "1",
"Auth": "content/articleList",
},
{
"item": "2",
"Auth": "content/articleList",
}],
"menu2": [
{
"item": "3",
"Auth": "publish/cacheSetting",
},
{
"item": "4",
"Auth": "publish/juggleList",
}]
}
You could do like below:
<div ng-repeat="(key, menu) in menus">
{{ key }}
<div ng-repeat="item in menu">
{{item.item}} : {{item.Auth}}
</div>
</div>
If you have a Service and want to use it in a Controller then you'd do the following to load JSON in the service, and call it from a Controller.
App.factory("MenuService", [ '$http', function($http) {
return {
getMenus: function() {
return $http.get( '/menuService' );
}
}
}]);
App.controller("SomeController", ['$scope', 'MenuService', function($scope,MenuService) {
$scope.doSomething = function() {
MenuService.getMenus().success( result ) {
$scope.menu1 = result.menu1;
$scope.menu2 = result.menu2;
// You got menu1 and menu2 now do something
}
}
}]);

Categories

Resources