My question is
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
My Code
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app='myApp' ng-controller='HttpController'>
{{detail.name}} <br/>
{{detail.address}} <br/>
{{detail.country}}<br/>
</div>
<script>
var hotelid=$('select#hotel_property option:selected').val();
var data = {};
data.Hotelid = hotelid;
data.Action = "hotel_property";
var helloApp = angular.module("myApp", []);
helloApp.controller("HttpController", function($scope, $http) {
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
});
</script>
<select id="hotel_property">
<option value="111">Taj hotel</option>
<option value="222">oberoi</option>
<option value="333">JW marriot</option>
<option value="444">Grand Maratha</option>
</select>
By deafult I am getting result for 1st hotel, how to get results on onchange of hotels dropdown by using angularjs directives ?
You'll have to do something on these lines.
Use ng-options to populate hotel list
Use ng-model to bind the selected value to some variable
Use ng-change to trigger a function to handle the change.
<select id="hotel_property" ng-model="selectedHotel"
ng-change="fetchInfo(selectedHotel)"
ng-options="hotel.name for hotel in hotels">
<option value="">-- please select -- </option>
</select>
and your controller might look like this.
Defile $scope.hotels with array of hotel id and name.
define a function to fetch hotel information.
helloApp.controller("HttpController", function($scope, $http) {
$scope.hotels = [{
id: 111,
name:'Taj hotel'
},{
id: 222,
name:'oberoi'
},{
id: 333,
name:'JW marriot'
},{
id: 444,
name:'Grand Maratha'
}];
$scope.fetchHotelInfo(hotel){
var data = {};
data.Hotelid = hotel.id;
data.Action = "hotel_property";
$http({
method: 'POST',
datatype:"json",
header: {
"contentType": 'application/json'
},
data: JSON.stringify(data),
url: '/ajax',
}).success(function(data, status, headers, config) {
$scope.detail = data.hotel_details;
}).error(function(data, status, headers, config) {
alert( "failure");
});
}
});
(Copy pasting code might not work)
Hope this helps!
You can use ng-model directive to store the selected value in the scope and use ng-change to fire the ajax query with the model value as parameter.
https://docs.angularjs.org/api/ng/directive/select
Related
I would like to have a selected option in the dynamic select box.
select box not showing any value as selected
$http({
method: 'GET',
url: $rootScope.API_URL + 'branchesShow/' + $routeParams.id,
}).then(function successCallback(response) {
$scope.city_id = response.data.data.city_id;
}, function errorCallback(response) {
// console.log(response);
});
$http({
method: 'GET',
url: $rootScope.API_URL + 'citySelectList',
}).then(function successCallback(response) {
$scope.cities = response.data.data;
console.log($scope.cities);
}, function errorCallback(response) {
console.log(response);
});
<select class = "form-control" ng-model="city_id" ng-options="c.id as c.title for c in cities">
</select>
I think your $scope.city_id doesn't contain an appropriate id value, as i can see you have ng-model directive and an option should be selected if the value in city_id matches an id of an object in your list.
Check if there is something wrong in the data, here is a little snippet to help you :
angular.module('myApp', [])
.controller('MyCtrl', function ($scope) {
$scope.cities = [
{
id: 1,
title: 'City 1'
},
{
id: 2,
title: 'City 2'
},
]
$scope.city_id = 1;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select class = "form-control" ng-model="city_id" ng-options="c.id as c.title for c in cities">
</select>
</div>
I am new in Angular and trying to POST data , but I am getting undefined status. My JSON raw body is like this :
{
"Name": "Something",
"Description": "Something",
"Data": []
}
Name and description is from user input field and Data will be used later to push another JSON object in the array.
I tried but not getting exact output.
Controller:-
app.controller('postController', ['$scope', '$http', 'appService', function ($scope, $http, AppService) {
$scope.addInfos = [{
Name: $scope.name,
Description: $scope.description,
Data: []
}];
$scope.Create = function () {
$scope.addInfos.push({
'Name': $scope.Name,
'description': $scope.Description,
'Data': []
});
$scope.dataObj = {
Name: $scope.name,
Description: $scope.description,
Data: []
};
$http({
method: 'POST',
url: 'http://192.120.27.8:2000/api/Add',
data: $scope.dataObj
}).then(function (data, status, headers, config) {
alert("success");
console.log(data + $scope.Name + $scope.Description);
}, function (data, status, headers, config) {
alert("error");
});
$scope.name = '';
$scope.Description = '';
};
HTML page :-
<div class="input-group col-md-10">
<span class="input-group-addon" id="reg_input" >Name</span>
<input type="text" class="form-control" placeholder="" ng-model="addInfos.name">
</div>
<div class="input-group sepH_b col-md-10">
<span class="input-group-addon" id="reg_input" >Description</span>
<textarea name="reg_textarea" id="reg_textarea" cols="10" rows="3" class="form-control" ng-model="addInfos.description"></textarea>
</div>
<div class="col-md-4">
<a style="" class="btn btn-md btn-primary" ng-click="Create(addInfos)">Create</a>
</div>
The output which I can see in my console is [object Object]. What mistake am I doing here ?
NOTE:- Here I didn't mentioned Data: field as it will be predefined array as of now like this {data:[]} need to inject and pass Name and Description in JSON as I mentioned above.
SECOND also I need to push this over all output data to the Service to store for further use.
Thanks guys , now I can able push necessary datas inside the JSON I did second work around .
$scope.addInfos = {Data: []};
$scope.Create = function() {
$http({
method : 'POST',
url : 'http://192.120.27.8:2000/api/Add',
data : $scope.addInfos
}).success(function(data, status, headers, config) {
growl.success("Created a new File");
console.log(data);
},function (data, status, headers, config) {
growl.error("Something is wrong");
});
};
My second concern is still there , now how to push these data to a service. var something =[];?
Here is the working code:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'World';
$http({
url: 'http://landregistry.data.gov.uk/landregistry/query',
headers: { 'Content-type' : 'application/x-www-form-urlencoded',
'Accept' : 'application/sparql-results+json' },
method: "GET",
params: {
query : "select * where {?s a ?o} limit 10",
format: "json"
}
})
.success(function(data, status, headers, config) {
$scope.results = data.results.bindings;
// this callback will be called asynchronously when the response is available
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs or server returns response with an error status.
});
});
http://plnkr.co/edit/LfkIPZRsZ4QHTfq2A2vc?p=preview
My doubt is how to store for instance, all s.values in an array such that the array can be further used to populate a drop down menu without having to save the JSON output to an external file.
Thanks.
You are already storing the results as a list in $scope.results.
To use the values for s in a dropdown menu, for example, you can do this:
<select ng-options="item as item.s.value for item in results" ng-model="selected"></select>
Plunkr
I have a drop-down menu populated with ng-options.
<label class="item item-input item-select">
</div>
<div class="input-currencies">
Select Currency
<select ng-options="c.code as c.name for c in currencies" ng-model="codeMod" ng-change="currencyChange(codeMod)">
</select>
</label>
How do I get the value c.code to be the property of the variable named selectedCurrency?
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
var selectedCurreny = "" // I want get dropdown code in this variable depending on the selected currency so I make changes in the API
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: selectedCurreny }
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
First, you have to change c.code as c.name for c in currencies in the ng-options attribute, you can't use a property here, it becomes c as c.name for c in currencies
Then, since you specified ng-model="codeMod", you can watch that variable in your controller, which becomes the following :
.controller('CurrencyController', function($scope, $http) {
var ngb_currencies = 'http://lari.jumpstart.ge/en/api/v1/nbg_currencies?callback=JSON_CALLBACK'
$http.jsonp(ngb_currencies).success(function(currency) {
$scope.currencies = currency.results;
})
.error(function(data) {
alert("ERROR");
});
$scope.$watch('codeMod', function(newSelectedCurreny) {
$http({
method: 'jsonp',
url: 'http://lari.jumpstart.ge/en/api/v1/nbg_rates?callback=JSON_CALLBACK',
params: { currency: newSelectedCurreny}
}).success(function(data, status , header, config) {
console.log('success');
$scope.result = data.result;
console.log('success');
}).error(function(data, status , header, config) {
console.log('error');
});
}
}
I have an ng-repeat of employees. One of the result fields returned is an employee number e.g. "12345".
How can I perform an ajax lookup and replace the employee number with the corresponding name?
Example: /_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '12345'
would return: "Doe, John".
I've tried using a filter but nothing ever gets displayed even though I can see results returned.
<div ng-repeat="emp in employees"">
<i class="fa fa-user"></i> {{emp.id}}
</div>
app.filter('getName', function($http) {
return function(id){
if (id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data, status, headers, config) {
userInfo = data.d.results[0].pn;
console.log(userInfo);
}).error(function (data, status, headers, config) {
userInfo = "0";
});
return userInfo;
}
};
});
The filter function is synchronous, while the $http call is asynchronous. The success callback isn't even going to be executed until after the filter function has already returned, so it looks like the return value will be undefined.
An angular filter isn't really appropriate for loading data from an API, and there's an easier approach. Add userInfo to the employees array in the appropriate service/factory/controller (that's up to how you're organizing your code, but the controller where you set $scope.employees is the quick and dirty option). Something like a forEach through the array making an API call for each one and setting employee.userInfo in the success callback:
app.controller('EmployeeController', function($scope, $http) {
// $scope.employees is initialized somehow
$scope.employees.forEach(function (employee) {
if (employee.id) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('allStaff')/items?$select=fullName&$filter=userid eq '"+employee.id+"'";
$http({
method: 'GET',
url: url,
cache: true,
headers: { "Accept": "application/json;odata=verbose" }
}).success(function (data) {
employee.userInfo = data.d.results[0].pn;
}).error(function () {
employee.userInfo = "0";
});
}
});
});
And in your template:
<div ng-repeat="emp in employees">
<i class="fa fa-user"></i> {{emp.userInfo}}
</div>
It's up to you to figure out what to do before the ajax request is finished, while emp.userInfo is undefined - hide the element, show a placeholder, etc.