Returning REST Data To Another Function - angularjs

So I am incorporating AngularJS into a SharePoint page that I am creating. I have a function that gathers information from a list in SharePoint via a REST function. What it is supposed to do is populate a table with the data it retrieves from the REST call. It does this fine, however, one of the fields is a 'Person or Group' field and rather than returning the name of the person, it returns their ID which is fine but it calls for me to perform another REST call on another list. I have successfully done so and filtered out the results based on the users ID. What I did was pass a user ID to a function that calls the REST function to the list that contains the users name and then wrote an if statement basically saying if the passed ID equals a given element ID, display the the users name. The problem I am having is while I have retrieved the correct data, I am not able to return the data and I believe the reason why is because I am trying to return data from a nested functions. I have a function and within that function an $http.success function. The data I am trying to retrieve resided in the $http.success function. Sorry if this question is hard to follow but hopefully taking a look at the below code will help to clear things up.
P.S. When I alert the code from the 'displayProjDetails' function I receive an undefined message, but when I alert it from the 'getUser' function it displays the data properly.
Thanks in advance for any assistance.
ANGULAR CODE:
// Function to display Project Details Data
$scope.displayProjDetails = function() {
$http({type: "GET", url:"http://mysiteurl/_api/web/lists/getbytitle('Project%20Details')/items?$top=5000", headers: { "ACCEPT": "application/json;odata=verbose"}})
.success(function(data) {
$scope.results = data.d.results;
$scope.details = [];
var full_funded;
for(i=0; i < data.d.results.length; i++) {
if(data.d.results[i].gibi == $scope.selectedProject.id) {
alert($scope.getUser(data.d.results[i].Project_x0020_POCId)); // CALL TO FUNCTION I AM WORKING ON (LOCATED AT THE BOTTOM OF THE PAGE)
if(data.d.results[i].Fully_x0020_Funded == true) {
full_funded = "Yes";
} else {
full_funded = "No"
}
$scope.details.push({id: data.d.results[i].gibi, poc: data.d.results[i].Project_x0020_POCId, code_poc: data.d.results[i].Code_x0020_312_x0020_POCId,
perc_complete: data.d.results[i].OData__x0025__x0020_Complete, funded: full_funded, pop_from: data.d.results[i].PoP_x0020_From,
pop_to: data.d.results[i].PoP_x0020_To});
}
};
});
}
// Function to retrieve the name of the Point of Contact (Currently working on this...)
$scope.getUser = function(value) {
$http({type: "GET", url: "http://mysiteurl/_api/web/siteusers?$top=5000", headers: { "ACCEPT": "application/json;odata=verbose"}})
.success(function(data) {
$scope.results = data.d.results;
$scope.user_attributes = [];
for(i=0; i < data.d.results.length; i++) {
if(data.d.results[i].Id == value) {
return data.d.results[i].Title;
}
};
});
}
HTML CODE
<div class="col-lg-9" id="project_details_table">
<h3>Project Details</h3>
<table class="table table-striped">
<thead>
<tr>
<th>Project ID</th>
<th>PoC</th>
<th>Code 2532 PoC</th>
<th>% Complete</th>
<th>Fully Funded</th>
<th>PoP From</th>
<th>PoP To</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="detail in details">
<td data-ng-bind="detail.id"></td>
<td data-ng-bind="detail.poc"></td> <!--TRYING TO REPLACE THIS WITH THE USER'S NAME INSTEAD OF THE USER'S ID-->
<td data-ng-bind="detail.code_poc"></td>
<td data-ng-bind="detail.perc_complete"></td>
<td data-ng-bind="detail.funded"></td>
<td data-ng-bind="detail.pop_from | date:'yyyy/MM/dd'"></td>
<td data-ng-bind="detail.pop_to | date:'yyyy/MM/dd'"></td>
</tr>
</tbody>
</table>
</div>
UPDATE:
Upon making the recommended changes to my code, my data is displayed as follows...
As you can see, what I am trying to do is replace the '[object Object]' with the proper name. Here it is just adding new rows to the table rather than placing the name in its correct location. Here is my updated code...
$scope.getUser = function(value) {
return $q(function(resolve, reject){
$http({type: "GET", url: "http:mysiteurl/_api/web/siteusers?$top=5000", headers: { "ACCEPT": "application/json;odata=verbose"}})
.success(function(data) {
$scope.results = data.d.results;
for(i=0; i < data.d.results.length; i++) {
if(data.d.results[i].Id == value) {
resolve(data.d.results[i].Title);
}
};
});
});
}
// Function to display Project Details Data
$scope.displayProjDetails = function() {
$http({type: "GET", url:"http:mysiteurl/_api/web/lists/getbytitle('Project%20Details')/items?$top=5000", headers: { "ACCEPT": "application/json;odata=verbose"}})
.success(function(data) {
$scope.results = data.d.results;
$scope.details = [];
$scope.name = [];
var full_funded;
for(i=0; i < data.d.results.length; i++) {
if(data.d.results[i].gibi == $scope.selectedProject.id) {
$scope.name = $scope.getUser(data.d.results[i].Project_x0020_POCId).then(function(user){$scope.details.push({poc: user});});
if(data.d.results[i].Fully_x0020_Funded == true) {
full_funded = "Yes";
} else {
full_funded = "No"
}
$scope.details.push({id: data.d.results[i].gibi, poc: $scope.name, code_poc: data.d.results[i].Code_x0020_312_x0020_POCId,
perc_complete: data.d.results[i].OData__x0025__x0020_Complete, funded: full_funded, pop_from: data.d.results[i].PoP_x0020_From,
pop_to: data.d.results[i].PoP_x0020_To});
}
};
});
}

The problem is that your are working with async calls, so you can't return data, because the alert don't wait for the promise response, so one way to solve the problem is to return the promise from getUser:
return $http ...
then in the alert :
alert($scope.getUser(data.d.results[i].Project_x0020_POCId).then(function(name){return name;}));

$scope.getUser = function(value) {
return $q(function(resolve, reject){
$http({type: "GET", url: "http://mysiteurl/_api/web/siteusers$top=5000",
headers: { "ACCEPT": "application/json;odata=verbose"}})
.success(function(data) {
$scope.results = data.d.results;
$scope.user_attributes = [];
for(i=0; i < data.d.results.length; i++) {
if(data.d.results[i].Id == value) {
resolve(data.d.results[i].Title);
}
};
});
}
$scope.getUser(data.d.results[i].Project_x0020_POCId)
.then(function(user){
alert(user)
});

Related

Get Value of column by API in angular

I want to get status value from API in my grid made in angular js. Below is the code, I applied in my view file:
<tr ng-repeat="item in list">
<td>{{item.id}}</td>
<td class="text-center" ng-init="statusUpdate(item.id ,$index)">
</td>
<td>{{myVar[$index]}}</td>
</tr>
Then in my controller I added:
app.controller('MerchantController', function ($scope, MerchantService, Alert, toaster) {
$scope.statusUpdate = function (id, index) {
var api = MerchantService.statusUpdate(id, index).then(function (response) {
console.log($scope.myVar[index]);
$scope.myVar[index] = response.data;
console.log($scope.myVar[index]);
});
};
});
In my service file, I added:
app.service('MerchantService', function(API, $stateParams, $q,$http) {
this.statusUpdate = function(item,index) {
return $http({
url: 'http://10.10.10.7/petca_magento/integration/vendor/vendor/id/' + item,
method: "GET",
});
};
});
I want to get of status field dynamically based on the user id in {{myVar[$index]}}

Angular - Trying to access value outside of $http get success and use it for a filter value

I'm building a silly little Football app. On the first page, I am trying to load the country's top division standings and the coming week's fixtures.
I retrieve the data, using a RESTful Web Service and so is done asynchronously. The table is fine, but not the fixtures.
There is an array of fixture objects, within them, there's a 'matchday' and 'status' property. If you look at the 'this.getFixtures' function, look at the success code block. What I am trying to do is only display the fixtures for a certain match day. If there is one game left to be played on a certain matchday, then I only want that fixture displayed. If not, display next matchday's fixtures.
The 'status' property typically has a value of 'SCHEDULED' or 'FINISHED'. In the success code block I am saying:
Loop through all fixtures retrieved.
If this fixture is scheduled, that means, we're on the matchday for this fixture.
In which case, break loop.
I am then trying to use that value outside the get method, but I keep getting undefined. Is there any way to access that value outside the success block?
I'll use the $scope.matchDay function as the filter.This will help me to only display scheduled fixtures in that matchday with ng-repeat.
Anyway, sorry for the long winded post, but here's the code:
HTML:
<div class="grid-x">
<div class="medium-8 medium-offset-2 cell">
<div id="premier-league-banner">
<div class="banner-shade">
<div class="grid-x">
<div class="medium-5 cell">
<table>
<tr ng-repeat="team in premierLeagueTable.standing | limitTo: 6">
<th>{{ $index + 1 }}</th>
<td><img class="prem-thumbnail" src="{{ team.crestURI }}" /></td>
<th>{{ team.teamName }}</th>
<th>{{ team.playedGames }}</th>
<th>{{ team.goalDifference }}</th>
<th>{{ team.points }}</th>
</tr>
</table>
</div>
<div class="medium-2 cell">
<img src="images/prem-logo.png" />
</div>
<div class="medium-5 cell">
<table>
<tr ng-repeat="fixture in premierLeagueFixtures.fixtures | filter:{matchday: 10}">
<th>{{fixture.homeTeamName}}</th>
<td>vs</td>
<th>{{fixture.awayTeamName}}</th>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
Angular JS
// MODULE
var quickEleven = angular.module('quickEleven', ['ngRoute', 'ngResource']);
// ROUTES
quickEleven.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'pages/home.htm',
controller: 'homeController'
})
});
// CONTROLLERS
quickEleven.controller('homeController', ['$scope', '$resource', '$log', 'footballData', function($scope, $resource, $log, footballData) {
function getMonday(date) {
var day = date.getDay() || 7;
if( day !== 1 )
date.setHours(-24 * (day - 1));
return date;
}
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
var thisMonday = getMonday(new Date);
var nextMonday = getMonday(new Date);
nextMonday.setDate(nextMonday.getDate() + 7);
$log.info("Boom! " + convertDate(thisMonday));
$log.info("For! " + convertDate(nextMonday));
$scope.premierLeagueTable = footballData.getLeagueTable("http://api.football-data.org/v1/competitions/:competitionId/leagueTable", 445);
//http://api.football-data.org/v1/competitions/:competitionId/fixtures?timeFrameStart=2018-03-01&timeFrameEnd=2018-03-05
//"http://api.football-data.org/v1/competitions/:competitionId/fixtures/?matchday=9"
$scope.premierLeagueFixtures = footballData.getFixtures("http://api.football-data.org/v1/competitions/:competitionId/fixtures?timeFrameStart=" + convertDate(thisMonday) + "&timeFrameEnd=" + convertDate(nextMonday), 445);
$log.info($scope.premierLeagueFixtures);
$log.info($scope.premierLeagueTable);
$scope.matchdayValue = 9;
$scope.matchDay = function() {
return footballData.getMatchday();
};
}]);
quickEleven.service('footballData', ['$resource', '$log', function($resource, $log) {
//Referring to the latest matchday with the status as 'SCHEDULED'
var self = this;
var test;
self.latestScheduledMatchday = 0;
self.getMatchday = function() {
$log.info("This is: " + test);
return self.latestScheduledMatchday;
}
this.getLeagueTable = function (footballUrl, compId) {
this.footballAPI =
$resource(footballUrl, {}, {
get: {
method: "GET",
headers: {
"X-Auth-Token": "f73808b698e84dccbe4886da3ea6e755"
}
}
})
.get({
competitionId: compId
}, function(data) {
this.fussball = data;
}, function(err) {
$log.error(err);
});
return this.footballAPI;
};
this.getFixtures = function (footballUrl, compId) {
// var self;
this.footballAPI =
$resource(footballUrl, {}, {
get: {
method: "GET",
headers: {
"X-Auth-Token": "f73808b698e84dccbe4886da3ea6e755"
}
}
})
.get({
competitionId: compId
}, function(data) {
// self = data.fixtures;
self.latestScheduledMatchday = data.fixtures[0].matchday
for (var i = 0; i < data.fixtures.length; i++) {
var fixture = data.fixtures[i];
if (fixture.status == 'SCHEDULED') {
test = fixture.matchday;
break;
}
}
$log.info("Dollar signs... " + test);
}, function(err) {
$log.error(err);
});
return this.footballAPI;
};
}]);
I see 2 issues so far. One on the note of undefined values is your service might not be getting implemented correctly. AFAIK you should be returning the service in the "function($resource, $log) {" function.
Here's how I'd change it (note I've not tested this)
quickEleven.service('footballData', ['$resource', '$log', function($resource, $log) {
//Referring to the latest matchday with the status as 'SCHEDULED'
var wrappedService = {};
var test;
var latestScheduledMatchday = 0;
var getMatchday = function() {
$log.info("This is: " + test);
return latestScheduledMatchday;
}
wrappedService.getLeagueTable = function (footballUrl, compId) {
wrappedService.footballAPI =
$resource(footballUrl, {}, {
get: {
method: "GET",
headers: {
"X-Auth-Token": "f73808b698e84dccbe4886da3ea6e755"
}
}
})
.get({
competitionId: compId
}, function(data) {
wrappedService.fussball = data;
}, function(err) {
$log.error(err);
});
return wrappedService.footballAPI;
};
wrappedService.getFixtures = function (footballUrl, compId) {
wrappedService.footballAPI =
$resource(footballUrl, {}, {
get: {
method: "GET",
headers: {
"X-Auth-Token": "f73808b698e84dccbe4886da3ea6e755"
}
}
})
.get({
competitionId: compId
}, function(data) {
latestScheduledMatchday = data.fixtures[0].matchday
for (var i = 0; i < data.fixtures.length; i++) {
var fixture = data.fixtures[i];
if (fixture.status == 'SCHEDULED') {
test = fixture.matchday;
break;
}
}
$log.info("Dollar signs... " + test);
}, function(err) {
$log.error(err);
});
return wrappedService.footballAPI;
};
return wrappedService;
}]);
So instead of the function returning no service, you have your service wrapped and returned as I believe you were intending. I also removed references to "self" since your intention there (internal service variables) is more eloquently handled with var scoping in the function.
Second issue that you will see once your service is working.
$scope.premierLeagueTable = footballData.getLeagueTable("http://api.football-data.org/v1/competitions/:competitionId/leagueTable", 445);
This line does not return the request data, but returns the request object. In fact by the time $scope.premierLeagueTable is set, the request hasn't even completed yet. What you do get is access to a promise that you can put a callback function in. See the angular resource documentation for more info, specifically the third example in the user-resource section where you see .$promise https://docs.angularjs.org/api/ngResource/service/$resource#user-resource.
Whatever functionality you want to apply the data return to should live inside that .$promise.then(...) callback. I'm not entirely sure if the promise in there receives the response data, or your callback return. You'll have to read further or experiment to find that out.

Angular 1.6: Data not showing until scope function execute

Title might sound a bit strange but that's how it is.
Code:
angular.module('app')
.controller('TenantsCtrl', ['$scope', 'tenantsService','$window','loginService', function ($scope, tenantsService, $window, loginService) {
$scope.mode = "list";
$scope.g = [];
$scope.editTenant = {
firstName: "",
lastName: "",
room: "",
to: "",
from: ""
}
tenantsService.get().then((data) => {
data.tenants.map((tenant) => {
tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO')
tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO')
});
console.log(typeof data.tenants);
$scope.g = data.tenants;
console.log($scope.g)
}).catch((reason) => {
loginService.doLogout();
if(confirm(`${reason}. Please login`)) {
$window.location.href="#!/login";
}
})
$scope.showTenantForm = function(tenant) {
console.log($scope.g)
}
}]);
View:
<div class="page-header">
<h1>Cazati <button class="btn btn-xs btn-primary" ng-click="showTenantForm()">Cazeaza</button></h1>
</div>
<div class="row" ng-cloak>
{{g}}
<table class="table table-hover">
<thead>
<tr>
<th>Nume</th>
<th>Camera</th>
<th>Cazat din</th>
<th>Cazat pana la</th>
<th>Cazat de</th>
<!--<th>Status</th>-->
<th>Modifica</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in g">
<td>{{x.lastName}} {{x.firstName}}</td>
<td>{{x.room}}</td>
<td>{{x.to}}</td>
<td>{{x.from}}</td>
<td></td>
<td>
<button type="button" ng-click="editTenant(tenant.id)" class="btn btn-danger btn-xs">Modifica</button>
</td>
</tr>
</tbody>
</table>
</div>
Problem: data from table isn't shown. Strangely it gets shown only when press the button from header and the function gets called.
Data from service comes correctly.
Update: tenantsService
angular.module('app')
.service('graphQLService', ['baseUrl', 'loginService', function (baseUrl, loginService) {
var graphQLService = {};
graphQLService.sendQuery = function (query, vars) {
var self = this;
vars = vars || {};
return new Promise(function(resolve, reject) {
// use fetch to get the result
fetch(baseUrl + '/gql', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
vars,
authToken: loginService.getToken()
})
})
.then(function(response) {
var status = response.status;
if(status != 401) {
return response.json().then((res) => {
resolve(res.data);
})
} else {
reject(response.statusText);
}
if(response.status == 401) {
}
})
.catch(reject);
});
};
return graphQLService;
}]);
Add a $scope.$apply() after you get your response and you manipulate your data, and after that you assign your data to your g scope variable. So:
$scope.g = data.tenants;
$scope.$apply();
AngularJS already wraps a lot of its code inside the $scope.$apply method. This in order to trigger the $scope.$digest method, which is the one responsible for refreshing all the bindings inside the related scope and update the values and so the views.
For example, if you were using the custom $http service, it's executed inside the $scope.$apply, so you don't need to call it explicitly.
In your case, you are not using the standard $http, so you need to trigger it manually.
The code was working after calling the other function because the ng-click is wrapped inside the $apply as well, so it refreshes all the bindings in the scope.
If you want to read more about it, this is a pretty good article:
http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
I hope it helps
I think the problem is that data.tenants.map returns you a new array. You don't save the reference to it.
Have you tried to do this
$scope.g = data.tenants.map((tenant) => {
tenant.to = new Date(tenant.to).toLocaleDateString('ro-RO');
tenant.from = new Date(tenant.from).toLocaleDateString('ro-RO');
return tenant;
});
console.log(typeof data.tenants);
console.log($scope.g)

angularjs object list not binding to ng-repeat

I am using angular 1.5.5 with ui router 0.2.14. I have the view of employee list to be displayed. EmployeeList template is as follows:
<table class="employeeListContainer">
<tr ng-repeat="employee in employees">
<td>
<a ng-bind="employee.EmployeeId" class="employeeId"></a>
<!--ui-sref="employeeDetails{ employeeId: employee.EmployeeId }"-->
</td>
<td ng-bind="employee.FirstName"></td>
<td ng-bind="employee.LastName"></td>
</tr>
<tr>
<td colspan="3" class="paging">
<button ng-disabled="!IsPrevButtonEnabled" ng-click="prevPage()" class="prev-next"><</button>
<span ng-bind="PageNumber"></span>
<button ng-disabled="!IsNextButtonEnabled" ng-click="nextPage()" class="prev-next">></button>
</td>
</tr>
<tr>
<td colspan="3" class="paging">
<span ng-bind="ErrorMessage" ng-show="IsError"></span>
</td>
</tr>
</table>
I have configured the app as follows:
var app = angular.module('app', ['ui.router']);
app.config(function ($urlRouterProvider, $stateProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider.state('employeeList', {
url: '/List',
templateUrl: '../../Templates/EmployeeList.html',
controller: 'EmployeeListController',
resolve: {
employeeListRs: function (dataService) {
var employeeListRq = getEmployeeListRqInit();
return dataService.callApi('GetEmployees', 'post', [employeeListRq])
.then(function (data) { return data.data; });
},
employeeListRq: function(){
return getEmployeeListRqInit();
},
greeting: function ($q, $timeout) {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('Hello!');
}, 1000);
return deferred.promise;
}
}
});
$stateProvider.state('default', {
url: '/',
//templateUrl: '../../Templates/EmployeeList.html',
controller: 'defaultController'
});
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
var getEmployeeListRqInit = function () {
return {
PageNumber: 1,
PageSize: 10,
SessionId: "123"
};
}
});
dataService is a service that is wrapper to the original $http.post call. Controller code is as follows:
app.controller('EmployeeListController', function ($scope, employeeListRq, employeeListRs, greeting) {
$scope.PageNumber = employeeListRq.PageNumber;
$scope.PageSize = employeeListRq.PageSize;
$scope.IsError = !employeeListRs.IsSuccess;
$scope.TotalCount = (employeeListRs.EmployeeList == null) ? 0 : employeeListRs.EmployeeList.TotalCount;
$scope.employees = (employeeListRs.EmployeeList == null) ? null : employeeListRs.EmployeeList.Employees;
if ($scope.employees = null) return 1;
var remainder = $scope.TotalCount % $scope.PageSize;
var pageNumber = Math.floor($scope.TotalCount / $scope.PageSize);
var lastPageNumber = remainder > 0 ? pageNumber + 1 : pageNumber;
$scope.IsNextButtonEnabled = $scope.PageNumber != lastPageNumber;
$scope.IsPrevButtonEnabled = $scope.PageNumber != 1;
$scope.IsLoading = false;
$scope.ErrorMessage = employeeListRs.IsSuccess ? '' : employeeListRs.ErrorMessage;
});
I see while debugging in chrome that $scope.employees is set to an array containing 10 objects all with proper fields and values. Also the IsPrevButtonEnabled and IsNextButtonEnabled are set perfectly. The binding is reflected on UI too, perfectly.
But I don't see the table containing employees list. Any suggestions on what I am missing?
Note: I don't get any error on console.
A few things you can try:
(1) Not saying yours is incorrect, but the preferred way to bind the data would be to use expressions. So, instead of this:
<td ng-bind="employee.FirstName"></td>
try this:
<td>{{employee.FirstName}}</td>
(2) This line looks suspicious in your controller:
if ($scope.employees = null) return 1;
It looks like you are assigning a null value to $scope.employees instead of checking for null. I/my teams try to use angular.isDefined($scope.employees) when we want to check for existence.
What are you trying to accomplish with that line?
(3) This looks a little different than how I use services and how I see others use them:
resolve: {
employeeListRs: function (dataService)
It looks to me that employeeListRs returns a promise.
What I typically do is call the service (my angular service which in turn calls the $http service) from inside the controller and then handle the response (both expected and error responses). From there I push the data into the controller's model. I haven't yet mixed service calls into my state machines - I let the controllers make the service calls.
(4) What is inside this css class - employeeListContainer? Could there be something there hiding your table? You might want to share your html and css as well.

bind dropdown and set selected value using angularJS

I have a form which populates location data, using angularJS. The form has 3 dropdowns for Location Type, Time Zone and Parent. For an existing location, I want the attributes to be selected in the dropdowns when the data is loaded. However, in following implementation, the dropdowns are populated, but the values are not selected.
HTML:
<tr>
<td style="width:20%"><label for="locationType">{{'_LocationTypeLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.locationType.locationTypeId" data-ng-options="l.locationTypeDisplayName for l in vm.locationTypes track by l.locationTypeId" /></td>
<td style="width:20%"><label for="parent">{{'_LocationParentLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.parent" data-ng-options="l.locationName for l in vm.parentLocations track by l.locationId" /></td>
</tr>
<tr>
<td style="width:20%"><label for="timezone">{{'_TimeZonesLabel_' | i18n}}:</label></td>
<td style="width:25%"><select data-ng-model="vm.locationSettings.basicSettings.timeZone" data-ng-options="l.displayName for l in vm.timeZones track by l.timeZoneId" /></td>
<td></td>
<td></td>
</tr>
controller:
function loadLocationData() {
clientcontext.clientlookup.getAllPublic().then(function (data) {
for (var i = 0; i < data.results.length; i++) {
vm.locationTypes.push(data.results[i]);
}
clientcontext.location.getLocations(vm.clientId, 1)
.then(function (data) {
for (var i = 0; i < data.length; i++) {
vm.parentLocations.push(data[i]);
}
systemcontext.systemlookup.getTimeZones()
.then(function (data) {
for (var i = 0; i < data.length; i++) {
vm.timeZones.push(data[i]);
}
//set the location attributes
vm.locationSettings.basicSettings = basicSettingsFactory.init().then(function () {
systemcontext.systemlookup.getTimeZoneById(vm.locationSettings.basicSettings.timeZone)
.then(function (data) {
vm.locationSettings.basicSettings.timeZone = data;
});
});
});
});
});
}
the location attributes are populated using a separate factory, as - vm.locationSettings.basicSettings = basicSettingsFactory.init()
function basicSettingsFactory($q, $http, $route, $location, $rootScope, $window, common, clientcontext, localize) {
var basicLocationSettings = {};
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.id = data.locationId;
basicLocationSettings.parent = data.fkParentLocationId;
basicLocationSettings.locationType = data.locationType;
basicLocationSettings.locationName = data.locationName;
basicLocationSettings.locationDisplayName = data.locationDisplayName;
basicLocationSettings.locationCode = data.locationCode;
basicLocationSettings.isActive = data.activeStatus;
basicLocationSettings.timeZone = data.fkTimeZoneId;
});
}
return {
// Initializes the entire monitoring probe scope variables.
init: function () {
getLocationDetails();
return basicLocationSettings;
}
};
}
})();
Can someone please point out what I'm doing wrong, that doesn't set the selected value in the dropdowns?
Thanks in advance
UPDATE:
Could the issue be that, the attribute locationtype has a integer value like 3, but what's bound to the dropdown is a LocationType object?
Look your updated code, it might help you.
function basicSettingsFactory($q, $http, $route, $location, $rootScope, $window, common, clientcontext, localize) {
var basicLocationSettings = {};
// Need to put the default Ids for selection display.
//The code look like this
basicLocationSettings.id = default; //defaylt Id
function getLocationDetails() {
clientcontext.location.getLocationById($route.current.params.clientId, $route.current.params.id)
.then(function (data) {
basicLocationSettings.id = data.locationId;
basicLocationSettings.locationName = data.locationName;
basicLocationSettings.locationDisplayName = data.locationDisplayName;
});
}
return {
// Initializes the entire monitoring probe scope variables.
init: function () {
getLocationDetails();
return basicLocationSettings;
}
};
}
})();

Resources