Set certain option of a select - angularjs

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>

Related

Dynamically populate dropdown - 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>

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>

Angular custom search filter

I need to create a custom search filter for this scope. I tried the default filter function , doesn't works, Because I displayed status as string in HTML and it is not filtered the way I want it. If I type Normal in the textbox, nothing happens because the data is 0, 1 and 2. And if I search the purchase time which is in 2016/05/16 format cannot search also.
$scope.orderHistory = {[
"purchaseTime": 1437536718345,
"status": 1,
]};
app.filter('filterSearch', function () {
//what to do here??
});
<input type="text" ng-model="searchReview">
<div dir-paginate="order in orderHistory|filterSearch:searchReview">
<ul>
<li><p class="table-data2-h">{{ order.purchaseTime | date : 'yyyy/MM/dd'}} </p></li>
<li>
<span ng-if="order.status == 0 ">Stable</span>
<span ng-if="order.status == 1 ">Normal</span>
<span ng-if="order.status == 2 ">Serious</span>
</li>
</div>
At first, I saw some mistakes on your code, you can compare it below.
I'd suggest you to create a simple function to parse your properties accordingly your requirements only on initilization (which one for sure will be better to parse everytime when than custom filter is called), then you can use the normal filter.
See it working:
(function() {
'use strict';
angular
.module('app', [])
.constant('STATUS', {
0: 'Stable',
1: 'Normal',
2: 'Serious'
})
.controller('MainCtrl', MainCtrl);
MainCtrl.$inject = ['$scope', 'STATUS'];
function MainCtrl($scope, STATUS) {
$scope.orderHistory = [
{
"purchaseTime": 1437536718345,
"status": 1
},
{
"purchaseTime": 1431236718345,
"status": 0
},
{
"purchaseTime": 1099536718345,
"status": 2
},
{
"purchaseTime": 1439744718345,
"status": 1
}
];
function parseProperties() {
$scope.orderHistory.map(function(order) {
// You can do it with switch statement
// switch (order.status) {
// case 0:
// order.status = 'Stable';
// break;
// case 1:
// order.status = 'Normal';
// break;
// case 2:
// order.status = 'Serious';
// break;
// }
// or using a constant that you can define above
order.status = STATUS[order.status];
order.purchaseTime = new Date(order.purchaseTime).toLocaleDateString();
return order;
});
}
parseProperties();
}
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>
<body ng-controller="MainCtrl">
<input type="text" placeholder="Search..." ng-model="searchReview">
<div ng-repeat="order in orderHistory | filter: searchReview">
<ul>
<li>
<p class="table-data2-h" ng-bind="order.purchaseTime"></p>
</li>
<li ng-bind="order.status"></li>
</ul>
</div>
</body>
</html>
I hope it helps

default data not coming in dropdown using angular JS

I am trying to load data to select box in angular JS. Data are getting loaded but the default value is coming as empty as shown below. Can any one please help.
<option label="CURRENT" value="object:4">CURRENT</option><option label="description of Version 2" value="object:5">description of Version 2</option><option label="description of Version 3" value="object:6">description of Version 3</option><option label="description of Version 4" value="object:7">description of Version 4</option></select>
Please find my code below :
app.jsp
<!DOCTYPE html>
<html lang="en">
<body class="internal" >
<div id="contentContainer" class="stratum" data-ng-controller="appController">
<div id="businessDropDownDiv" class="column column.one-quarter-">
<div class="selectLabel">
<label for="businessSelect">Business Area</label>
</div>
<div>
<!-- <select ng-init="item.versionID=versions[0]" ng-model="item.versionID" ng-selected="0" ng-options="version.name for version in versions" required> -->
<select data-ng-init="business.data.businessId=business[0]" data-ng-model="business.data.businessId" data-ng-options="option.businessArea for option in business" class="filter">
</select>
</div>
</div>
</div>
</body>
<script type="text/javascript">
var contextPath = "<%= request.getContextPath() %>";
var appUrl = "<%= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() %>";
var isSessionExpired = false;
</script>
<!-- JavaScripts Require JS Library and App JS Files -->
<script type="text/javascript" data-main="<%=request.getContextPath() %>/resources/js/app/uptimeReport.js" src="<%=request.getContextPath() %>/resources/js/libs/requirejs/require.js"></script>
</body>
</html>
uptimeReport.js
'use strict';
requirejs.config(
{
/** set up any additional paths that are outside of your application base * */
paths:
{
angular: contextPath + '/resources/js/libs/angularJS/angular',
jquery: contextPath + '/resources/js/libs/jquery/jquery',
uptimeReportBarChart : contextPath + '/resources/js/app/uptimeReportD3BarChart',
uptimeReportD3LineChart : contextPath + '/resources/js/app/uptimeReportD3LineChart',
d3Chart: contextPath + '/resources/js/libs/d3Charts/d3',
d3pkChart: contextPath + '/resources/js/libs/d3Charts/pk'
},
/**
* The following is not required in this example, but it is an example of
* how to make non-AMD java script compatible with require
*/
shim: {
angular: {
exports: 'angular'
},
d3Chart: ['jquery'],
d3pkChart: ['d3Chart']
},
deps: ['app']
});
app.js
'use strict';
require([
'angular'
], function (angular) {
require([
'controller/environmentController',
'uptimeReportBarChart',
'd3Chart', 'd3pkChart',
'uptimeReportD3LineChart'
], function (appCtrl) {
angular.
module('myApp',[]).
controller('appController', appCtrl);
angular.bootstrap(document, ['myApp']);
console.log("in App.js");
});
});
environmentController.js
'use strict';
define([
'angular'
], function (angular) {
return ['$scope', '$http',
function($scope, $http) {
console.log("in controller123.js");
var businessUrl="http://localhost:8080/UptimeReport/services/getBusinessAreas";
$http.get(businessUrl).then(function(response) {
$scope.business = [ {
"id": "0",
"businessArea": "CURRENT",
"businessId": "CURRENT"
},
{
"id": "114",
"businessArea": "description of Version 2",
"businessId": "version2"
},
{
"id": "126",
"businessArea": "description of Version 3",
"businessId": "version3"
},
{
"id": "149",
"businessArea": "description of Version 4",
"businessId": "version4"
}] ;
});
}];
});
I took a look at the code and made some corrections to make it work and understand your problem. Now coming to your problem solution. Add this line after retrieving the data using $http,get.
$scope.item={versionID:$scope.versions[0]};
For reference you can check the fiddle link where I have added the line and updated the code: https://jsfiddle.net/prijuly2000/43cs0y0c/
The problem with your current approach is that the model for select box is not initialized so it displays empty in the box as the dropdown will display the current value set to the model. So above line sets the initial value for the model which renders the first option selected in the view.
Let me know if this is not something that you didnt seek and I misunderstood the problem

Using ng-repeat in order to iterate over object properties and ordering by value instead of key with ng 1.3

I am in reference to the angular documentation about ngRepeat and iterating over object properties which states:
<div ng-repeat="(key, value) in myObj"> ... </div>
You need to be aware that the JavaScript specification does not define
the order of keys returned for an object. (To mitigate this in Angular
1.3 the ngRepeat directive used to sort the keys alphabetically.)
Say I have the following object:
var myObj = {FOO: 0, BAR: 1};
and want it to be ordered by value (i.e. 0 & 1) instead of keys. How can this be achieved with angular? (I use angular 1.3 by the way).
I have tried:
ng-repeat="(key, value) in myObj | orderBy:value"
But it does not work...
Can anyone please help?
Just as with filter, orderBy works with arrays only. One simple solution is to use a function that returns an array from an object:
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<input type="text" ng-model="searchText"/>
<ul ng-init="nameArray=objArray(names)">
<li ng-repeat="x in nameArray | filter:searchText | orderBy: 'value.name'">
{{x.value.name}}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.searchText='';
$scope.names = {
"1": {
"name": "some"
},
"2": {
"name": "values"
},
"3": {
"name": "are"
},
"4": {
"name": "there"
},
"5": {
"name": "here"
}
};
$scope.objArray=function (obj) {
var result=[];
for (var key in obj) {
result.push({
key: key,
value: obj[key]
});
}
return result;
}
});
</script>
</body>
</html>
I believe the best and elegant solution is to make a filter that changes your object into an array. Therefore you can reuse it thought all your project in your template without coding any js.
Here is what the filter would look like:
(function () {
'use strict';
angular.module('app').filter('toArray', toArray);
toArray.$inject = [];
function toArray() {
return toArrayFilter;
function toArrayFilter(input) {
if (angular.isArray(input)) return input;
var list = [];
angular.forEach(input, iterateProperty, list);
return list;
function iterateProperty(elt, key) {
this.push({ key: key, value: elt });
}
}
}
})();
and here is how you would use it in your html template:
<div ng-repeat="element in myObject | toArray | orderBy:value">
{{element.key}}:
<pre>{{element.value | json}}</pre>
</div>

Resources