Dynamically populate dropdown - AngularJS - angularjs

I have a dropdown in angularJS defined as:
$scope.Ids = [ {
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
} ];
$scope.Id = $scope.Ids[0];
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
My requirement is to dynamically populate these Ids from DB.
I have a spring controller that makes a call to DB:
$http({
'url' : '/getIds',
'method' : 'POST',
'headers' : {
'Content-Type' : 'application/json'
},
'params' : data
}).then(function(response) {
$scope.Ids = response.data.Ids;
});
and yields a list:
["ID-100", "ID-200", "ID-300"]
0: "ID-100"
1: "ID-200"
2: "ID-300"
My $scope.Ids will now be having the new list. I need to map this list to my $scope.Ids in dropdown format and make my dropdown display the first record.
Can someone give an idea on how to achieve this?

Your code is already correct, however your approach should be like below.
DEMO
var app = angular.module('todoApp', []);
app.controller("dobController", ["$scope",
function($scope) {
$scope.Ids = [{
id : 'ID-100',
name : 'ID-100'
}, {
id : 'ID-200',
name : 'ID-200'
}, {
id : 'ID-300',
name : 'ID-300'
}];
$scope.Id = $scope.Ids[0];
}]);
<!DOCTYPE html>
<html ng-app="todoApp">
<head>
<title>To Do List</title>
<link href="skeleton.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<script src="MainViewController.js"></script>
</head>
<body ng-controller="dobController">
<select class="custom-select" ng-model="Id" ng-options="choice.name for choice in Ids"></select>
<div>
<h1> Selected one is : {{Id}} </h1>
</div>
</body>
</html>

Related

Set certain option of a select

I am trying to update a row in table, so in edit mode I need to fetch the existing data and populate them in a card. Its fine with textboxes but trouble with selects. I cannot get the select to show the existing option fetched.
My mark up:-
<select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
</select>
here's how I am initializing the select: -
$scope.segment = [ {
"text" : "B2B",
"value" : "0"
}, {
"text" : "B2C",
"value" : "1"
} ];
And here's how I am trying to set its value (tried two ways) :-
1)
$scope.u_segment = selected.segment;
2)
$scope.u_segment.value = selected.segment;
But it(select) still stays blank, though others (text fields) are populated.
You are selecting obj, so your selected.segment must be the entire object: {"text" : "B2B", "value" : "0"} (for example)
Here is a demo:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var selected = {
"segment": {
"text": "B2C",
"value": "1"
}
};
$scope.segment = [{
"text": "B2B",
"value": "0"
}, {
"text": "B2C",
"value": "1"
}];
$scope.u_segment = selected.segment;
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
</select>
{{u_segment}}
</div>
</body>
</html>
If you don't know the entire object, but only some property of it (like value), you need to search for it (in a loop):
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
var selected = {
"segment": "0"
};
$scope.segment = [{
"text": "B2B",
"value": "0"
}, {
"text": "B2C",
"value": "1"
}];
for(var i=0; i<$scope.segment.length; i++){
if($scope.segment[i].value == selected.segment){
$scope.u_segment = $scope.segment[i];
}
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="textbox-style4" data-ng-options="obj.text for obj in segment track by obj.value" data-ng-model="u_segment">
</select>
{{u_segment}}
</div>
</body>
</html>

Angular UI grid - Translate grid on fly

I am using angular ui-grid. I want to translate the grid on fly. For example my current language is English. The grid gets rendered in English. Now I switch to french. I want all my menu options to be translated to french. How can I achieve this? This is my link to plunkr.
http://plnkr.co/edit/tpdNYirUEIF3RL0kf2d7?p=preview
Here is my sample code
HTML
<!doctype html>
<html ng-app="app">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/csv.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/pdfmake.js"></script>
<script src="http://ui-grid.info/docs/grunt-scripts/vfs_fonts.js"></script>
<script src="http://ui-grid.info/release/ui-grid-unstable.js"></script>
<script src="https://rawgithub.com/PascalPrecht/bower-angular-translate/master/angular-translate.min.js"></script>
<script src="app.js"></script>
<link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<body>
<div ng-controller="MainCtrl">
<select ng-model="lang" ng-options="l for l in langs"></select><br>
<div ui-i18n="{{lang}}">
<p>Using attribute:</p>
<p ui-t="groupPanel.description"></p>
<br/>
<p>Using Filter:</p>
<p>{{"groupPanel.description" | t}}</p>
<p>Click the header menu to see language. NOTE: TODO: header text does not change after grid is rendered. </p>
<div ui-grid="gridOptions" class="grid"></div>
</div>
</div>
</body>
</html>
My JS
var app = angular.module('app', ['ngTouch', 'ui.grid', 'pascalprecht.translate']);
app.controller('MainCtrl', ['$scope', 'i18nService', '$http', '$translate','$rootScope', function ($scope, i18nService, $http, $translate,$rootScope) {
$scope.langs = i18nService.getAllLangs();
$scope.lang = 'en'
$scope.gridOptions = {
columnDefs: [
{ displayName: 'NAME', field: 'name', headerCellFilter: 'translate' },
{ displayName: 'GENDER', field: 'gender', headerCellFilter: 'translate' },
{ displayName: 'COMPANY', field: 'company', headerCellFilter: 'translate', enableFiltering: false }
]
};
$http.get('https://cdn.rawgit.com/angular-ui/ui-grid.info/gh-pages/data/100.json')
.success(function(data) {
$scope.gridOptions.data = data;
});
}]);
app.config(function ($translateProvider) {
$translateProvider.translations('en', {
GENDER: 'Gender',
NAME: 'Name',
COMPANY: 'Company'
});
$translateProvider.translations('de', {
GENDER: 'Geschlecht',
NAME: 'Name',
COMPANY: 'Unternehmen'
});
$translateProvider.preferredLanguage('en');
});
The first screenshot refers to default language English. When I change my language to 'de' the grid menu options don't get translated. How can I make this happen?
To translate the Grid on the fly if you are using "Angular Translate", you should only refresh the Grid language when the angular-translate's event "$translateChangeSuccess" get fired like below:
// Get Fired when you change language using angular-translate
$rootScope.$on('$translateChangeSuccess', function (event, a) {
$scope.language = $translate.proposedLanguage() || $translate.use();
i18nService.setCurrentLang($scope.language); // Refresh the grid language
});
Do not forget to inject $rootScope and i18nService.
I needed to translate on the fly (without page refresh) those custom menu items too as well as "items per page" and such in the pager.
I also wrote an hack/workaround directly in the ui-grid source code so sharing if it might help someone else, at least until there will be an official patch.
first at grid definition a new event to handle language changed on
the fly (for example via angular dynamic locale):
onRegisterApi: function(gridApi) {
gridApi.registerEvent('language', 'changed');
gridApi.language.on.changed($scope, function(language) {
$rootScope.$gridLanguage = language;
});
then in a controller after language changed raise that event (in my
case on $localeChangeSuccess from angular dynamic locale) :
$scope.$on('$localeChangeSuccess', function (e, locale) {
$scope.$View.GridApi.language.raise.changed(locale);
});
and here the hacks, where the texts need a refresh, for example
adding in uiGridColumnMenu directive link function:
$scope.$watch('$parent.$root.$gridLanguage', function () {
if ($scope.$parent.$root.$gridLanguage !== undefined) {
$scope.menuItems = uiGridColumnMenuService.getDefaultMenuItems($scope);
}
});
or the same for uiGridPager:
$scope.$watch('$parent.$root.$gridLanguage', function () {
if ($scope.$parent.$root.$gridLanguage !== undefined) {
$scope.sizesLabel = i18nService.getSafeText('pagination.sizes');
$scope.totalItemsLabel = i18nService.getSafeText('pagination.totalItems');
$scope.paginationOf = i18nService.getSafeText('pagination.of');
$scope.paginationThrough = i18nService.getSafeText('pagination.through');
}
});
Working Plnkr
Add following method in controller:
$scope.changeLanguage = function (key) {
$translate.use(key);
};
Call this method with ng-change:
<select ng-model="lang" ng-options="l for l in langs" ng-change="changeLanguage(lang)"></select>

Append key value pair to angularjs object

I am getting json output from laravel 5.2 form request validation
My json output is:
{
"title": [
"The title field is required."
],
"description": [
"The description field is required."
],
"address.city": [
"City field is required"
]
}
Appending this output to object
var self = this;
self.error = {
address: {}
};
var onFailure = function (response) {
angular.forEach(response.data, function(value, key) {
self.error[key] = value[0];
});
};
I want to access this error object to my view, for "address.city", I can't access it using "ctrl.error.address.city", rest I can access
How to append object with key containing "." and show it in view?
Here is what you need. But its better not to have (.) in a property name. Instead you can use a underscore(_). Avoid using dot(.) as a chaaracter in property names.
var myApp = angular.module('MyApp', []);
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo['hello.There'] = "I'm foo!";
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp" ng-controller="MyCtrl">
{{foo["hello.There"]}}<br />
<input type="text" ng-model="foo['hello.There']" />
</div>
if you know the key name then the only way you can access it is by [].
Check the fiddle for more info.
https://jsfiddle.net/9f4mbh1h/1/
You need to change your code to this
in your controller
myApp.controller('MyCtrl', function ($scope) {
$scope.foo={};
$scope.foo "hi";
});
in html
<div ng-app="MyApp" ng-controller="MyCtrl">
<input type="text" ng-model="foo" /> </div>

option value not populated in angular js from the get object of spring controller

Simple requirement to populate the array object in the angular js option, the array object is populated from the spring controller.
The angular js has http get request, it seems the problem is that with the http get request, the reason, i had added test items option, when i include the http get the items option is not populated.
below is the code of my simple requirement.
view.jsp
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "Gopala";
$scope.lastName= "Krishnan";
$scope.items = [{name: 'one', age: 30 },{ name: 'two', age: 27 },{ name: 'three', age: 50 }];
$http.get('http://169.52.203.189:8080/LDODashBoard/AppView?appid=CV-APAC-CHECKOUT').success(function(data) {
$scope.appview = data;
});
});
</script>
<link rel="stylesheet" type="text/css" href="/LDODashBoard/css/mystyle.css" />
<meta charset="utf-8">
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>selected item is : {{firstName}}</p>
<p>selected item is : {{lastName}}</p>
<select ng-model="selectedItem" ng-options="item.name for item in items">
</select>
<select ng-model="selectedItem1" ng-options="appview1.oDATE for appview1 in appview">
</select>
</div>
Controller.java
#RequestMapping(value = "/AppViewJson",method=RequestMethod.GET,produces={"application/xml", "application/json"})
public ModelAndView monitorUnixProcessJson(
#RequestParam(value = "appid", required = false) String appviewid,
Model model, HttpServletResponse response) {
log.info("inisde AppViewJson json method");
List <AppViewBatchDetails> appviewbatchlist = null;
try {
if (!appviewid.isEmpty()) {
WebPageURLReader webpagereader = new WebPageURLReader();
webpagereader.extractNeededAppview(appviewid);
webpagereader.executeRetrieveAppviewDetailsWrapper();
appviewbatchlist = webpagereader.returnMatchedAppviewJobs();
}
//return the dummy outputdisplay page, show nothing
return (new ModelAndView("AppviewDisplayJsonPage","appviewbatch",appviewbatchlist));
}
catch (Exception e){
log.error("exception received here!!!!");
}
return (new ModelAndView(CommonConstants.OutputDisplayPage,"",""));
}
}

Angular.JS data binding

I have started learning angular.js but I am kind of having trouble understanding the data binding and scopes.
Here is my Html file :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"> </script>
<title>Egghead</title>
</head>
<body data-ng-app="myApp">
1. <div>
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
2. <div data-ng-controller="firstController">
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
3. <div data-ng-controller="secondController">
NAME : <input type = "text" name = "name" data-ng-model="data.name"/>
Typed Name : <b>{{data.name}}</b>
<br><br>
EMAIL: <input type = "email" name = "email" data-ng-model="data.email"/>
Typed Email : <b>{{data.email}}</b>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
Now when I have this module for my current html :
(function(){
var myApp = angular.module('myApp', []);
myApp.controller('firstController', function($scope, $rootScope) {
/*$rootScope.data = {name : "root", email : "root#gmail.com"};
$scope.data = {name : "Ishan", email : "soni.ishan.nitj#gmail.com"};*/
});
myApp.controller('secondController', function($scope) {
/*$scope.data = {name : "Divyan", email : "soni.divyan#gmail.com"};*/
});
})();
any changes that I make in any of the textbox for say the "name" input reflects and is bound everywhere. Example I make a change in the input text with name = "name" inside the second controller, the value in the text box for first also changes, but when I remove the comments from my javascript file, any change I make in the second controller's input box are not reflected in the first's input box. Why?
$rootScope is parent of all scopes, so if you assign property to it, it will be available everywhere in views. Every controller has $scope, you have two sibling controllers, so they have different scopes, if you want to share data between controllers, you shall use service. Like this:
myApp.factory('dataSrvc', function () {
return {
getData: function () {
return {
name : "Divyan",
email : "soni.divyan#gmail.com"
};
}
};
});
Then inject it into controllers:
myApp.controller('firstController', function($scope, dataSrvc) {
scope.data = dataSrvc.getData();
});
myApp.controller('secondController', function($scope, dataSrvc) {
scope.data = dataSrvc.getData();
});
In this case changes in first controller will not reflect on second and vice versa, because getData returns new instance of object every time (with same data).

Resources