I have this function selectHotel() which executes when the select box is clicked and I have used GET method to call data and display it on my view.
I have two options on my select area and it fetches different data for both of them. I want the data of my first option to be displayed when the page is loaded and not when I click the select box.
<div class="row">
<div class ="form_group">
<select ng-click="selectHotel()" class="form-control" ng-options='item as item.hotel_name for item in hotels.data' ng-model='current_Hotel'></select>
Check In:<input type="date">
Check Out:<input type="date">
</div>
<div class="col-md-6">
<h1>{{current_Hotel.hotel_name}}</h1>
<p>{{current_Hotel.hotel_description}}</p>
<img id="hotelImg" class="img img-responsive" ng-src="{{current_Hotel.image_url}}">
<btn class="btn btn-primary">Book a room </btn>
</div>
</div>
<div class="row" ng-repeat="x in roomdata.data">
<div class="well well-sm" >{{x.room_type}}Room Details
</div>
<h5>{{x.rack_price}}<br>Per room per night</h5>
Adult: <select>
<option>1</option>
<option selected="selected">{{x.max_people}}</option>
</select>
Child: <select>
<option>{{x.max_child}}</option>
</select>
</div>
Here is the controller
var app = angular.module('myApp', []);
app.controller('ctrl1', function ($scope, $http) {
$scope.current_Hotel = {
hotel_id: "",
hotel_name: "",
hotel_description: "",
exterior_image: "",
image_url: ""
};
$http({
url: '',
method: "POST",
data: 'postData',
headers: {
'Authorization': ''
}
}).then(function (response) {
$scope.hotels = response.data;
$scope.current_Hotel = $scope.hotels.data[0];
});
$scope.selectHotel = function () {
$http({
method: 'GET',
url: '&image_id=' + $scope.current_Hotel.exterior_image
}).then(function (response) {
var imgdata = response.data;
var imgdata1 = imgdata.data.image_name;
$scope.current_Hotel.image_url = "" + imgdata1;
});
$http({
method:'GET',
url: '&hotel_id=' +$scope.current_Hotel.hotel_id
}).then(function(response){
$scope.roomdata = response.data;
});
};
});
Change your HTMl to invoke a changeHotel when different option is selected.
Invoke changeHotel after all the hotels are loaded passing the first item in the hotel list. This will load the data for the first hotel as per your necessity.
HTML:
<select ng-options="hotel as hotel.name for hotel in hotels"
ng-model="currentHotel"
ng-change="changeHotel(currentHotel)">
</select>
<p>{{disp}}</p>
JavaScript:
$http.get('API_URL')
.then(function(res) {
$scope.hotels = res.data;
$scope.currentHotel = res.data[0];
$scope.changeHotel($scope.currentHotel);
});
$scope.changeHotel = function(hotel) {
$scope.currentHotel = hotel;
$scope.disp = "This is data for current hotel : " + $scope.currentHotel.name;
// stuffs ...
};
Check this CodePen Demo
Related
I have a GET function to list names, and another function that is triggered by an ng-click, that needs to update the ng-repeat where the lists of names are being at displayed by the get function. But it is not working. This is my code:
Container where the GET function displays:
<div class="container names-container" ng-controller='namesCtrl'>
<div ng-repeat='name in names.pData'>
<div class="name-box chiuv">
<p class="name-name">{{ name.name }} {{ name.last_name }}</p>
<p class="name-date">{{ name.date}}</p>
</div>
</div>
Search modal with the ng-click
<div class="output">
<input type="text" class="form-control" name="output" id="nameH" ng-model="inputName" placeholder="Search by name">
</div>
<div class="hebk"></div>
<button class="search-btn" ng-click="searchName()">SEARCH</button>
Functions
var fetch = angular.module('myapp', []);
fetch.controller('namesCtrl', ['$scope', '$http', function($scope, $http) {
$scope.getNames = function() {
$http({
method: 'get',
url: '<?= base_url(); ?>/display/getNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = response.data;
});
}
$scope.getNames();
$scope.searchName = function() {
$scope.names = '';
$http({
method: 'post',
data: {
name: $scope.inputName
},
url: '<?= base_url(); ?>/display/searchNames'
}).then(function successCallback(response) {
// Assign response to users object
$scope.names = [];
$scope.names = response.data;
});
}
}]);
Suppose there are two hotels in my options in select tags and I want my h1 to change when I select one of the options. How do I achieve this
I am using POST method to authorize and call data in my reservationCtrl and display the hotel_name in my select tags.
<div class="container">
<div class = "row" ng-controller="reservationCtrl">
<div class="form-group">
<label for="sel1">Select a Hotel:</label>
<select class="form-control" id="sel1">
<option ng-repeat="x in hotels.data">{{x.hotel_name}}</option>
</select>
</div>
</div>
And I am using GET method to call data from another API to display the hotel_name.
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data">{{x.hotel_name}}</h1>
</div>
</div>
</div>
Here is my showController and I want my hotel id to change like from 72 to 35 when I click one of the options so that it will call data from a different API and display a different name in the headers.
(function(){
angular
.module("reservationModule")
.controller("showCtrl", function($http, $scope, $log){
$http({
method: 'GET',
url: '&hotel_id=72'})
.then(function (response) {
$scope.hotel = response.data;
}, function (reason){
$scope.error = reason.data;
$log.info(reason);
});
});
})();
Here is the reservationController
(function(){
angular
.module("reservationModule")
.controller("reservationCtrl", function($http, $scope, $log){
$http({
url: '',
method: "POST",
data: 'postData',
headers:{ 'Authorization': 'value'}
})
.then(function(response) {
$scope.hotels = response.data;
}
);
});
})();
Yes you can add ng-change and achieve your functionality as below
JS code
var app = angular.module('myApp', []);
app.controller('ctrl1', function($scope) {
$scope.hotels = [{
name: 'Taj',
id: 1
}, {
name: 'Royal',
id: 2
}];
$scope.hotelInfo = {};
$scope.fetchData = function() {
// here call service which will fetch data and assign to hotel data
$scope.hotelInfo = {
address: 'London'
};
}
});
app.controller('ctrl2', function($scope) {
$scope.data = ''
});
HTML code
<div ng-app='myApp'>
<div ng-controller='ctrl1'>
<select ng-options='item as item.name for item in hotels' ng-model='hotel' ng-change='fetchData()'>
</select>
{{hotel}} - {{hotelInfo}}
</div>
</div>
Here is the link Jsfiddle demo
You need to call event on the select box which will call simple function which return the data like following
<select ng-options="size as size.name for size in sizes"
ng-model="item" ng-change="update()"></select>
write javascript code on the update function
Your can use ng-change on select of particular hotel.
In congroller :
$scope.showHotel = function(hotelName){
$scope.selectedHotel = hotelName;
}
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1 ng-repeat="x in hotel.data" ng-change="showHotel(x.hotel_name)">{{x.hotel_name}}</h1>
</div>
</div>
In view you you can edit like this if you have to display only one hotel name instead of ng-repeat:
<div class="row" ng-controller="showCtrl">
<div class="col-md-4">
<h1>{{selectedHotel}}</h1>
</div>
</div>
I wanted to make Spinner should appear when user clicks on Submit Button and Spinner should stop once the AJAX POST and GET request completed
Can you Please help me know How I make my below Angular Code to implement the feature.
Below is the Example I saw for Spinner in Angular
Demo
Below is my AngularJS code .
var app = angular.module("myApp", ["ngTable"]);
app.controller("Controller", ["$scope", "$http", "$window",
function ($scope, $http, $window) {
$scope.firstFunction = function () {
$http({
method: 'POST',
url: 'mainDeviceSite.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
$scope.cellularIPAddressValue = response.data.devices;
console.log($scope.cellularIPAddressValue);
//$scope.secondFunction(data);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
$scope.secondFunction = function () {
$http({
method: 'POST',
url: 'BEPEvents.php',
//headers : {'Content-Type':'application/x-www-form-urlencoded'},
data: {
accountnumber: $scope.accountnumber
},
}).then(function (response) {
var data = response.data;
$scope.post = response.data;
var x2js = new X2JS();
$scope.aftCnv = x2js.xml_str2json(response.data);
$scope.bepValues = $scope.aftCnv.EEPEvents.BlobData;
console.log($scope.bepValues);
}, function (error) {
var data = error.data;
console.log("Error" + data);
})
}
}
]);
HTML Code
<div class="example">
<div class="col-md-12">
<div class="row">
<div class="input-group form-search">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="firstFunction();secondFunction()" class="btn btn-primary">Submit</button>
</span>
<span id="message">{{message}}</span>
</div>
</div>
</div>
</div>
Try Following solution
This applicable for all http request that are use in angular controller. When you call http request then spinner and progress bar you shows
Demo
Refer this angular-loading-bar.
include the loading bar as a dependency for your app. If you want animations, include ngAnimate as well. note: ngAnimate is optional
angular.module('myApp', ['angular-loading-bar', 'ngAnimate'])
include the supplied JS and CSS file (or create your own CSS to override defaults).
<link rel='stylesheet' href='build/loading-bar.min.css' type='text/css' media='all' />
<script type='text/javascript' src='build/loading-bar.min.js'></script>
Hope this is help you
I am trying to paginate a potentially very long list of divs. I have things working fine without the pagination however when I try to implement pagination (using this as a sort of template: http://plnkr.co/edit/81fPZxpnOQnIHQgp957q?p=preview) I receive an error: TypeError: cannot read property 'slice' of undefined . As far as I can tell this is an issue involving the $scope.data variable since I am calling slice on $scope.data . I am not sure how to resolve this and get it working. I will post the working version without pagination followed by the erroneous version with pagination. The only differences in the controller are from the line filteredTodos onward. I am calling fetchAllSamples() which populated $scope.data before any other work is done with pagination so I'm not sure why it would be undefined. All help is much appreciated.
Erroneous pagination html:
<div>
<div>
<div class="col-md-12">
<div style="border: 1px solid #000000">
<div ng-repeat="item in filteredTodos" style="margin-left: 14px">
{{item.name}}
<br> <span style="font-size: 20px">{{item.description}}</span>
<br>
<hr>
</div>
</div>
</div>
<pagination ng-model="currentPage" total-items="data.length" max-size="maxSize" boundary-links="true"> </pagination>
</div>
</div>
and correct non-paginated:
<div>
<div>
<div class="col-md-12">
<div style="border: 1px solid #000000">
<div ng-repeat="item in data" style="margin-left: 14px">
{{item.name}}
<br> <span style="font-size: 20px">{{item.description}}</span>
<br>
<hr>
</div>
</div>
</div>
</div>
</div>
which use the following controller:
app.controller('SamplesQueryController','$scope','$http', function($scope, $http) {
$scope.newSampleName = {
sampleName: ''
};
$scope.attributes = [{
name: '',
value: ''
}];
$scope.sampleCount = 0;
$scope.addAttribute = function() {
var attribute = {
name: '',
value: ''
};
$scope.attributes.push(attribute);
}
$scope.showModal = false;
$scope.toggleModal = function() {
$scope.showModal = !$scope.showModal;
};
$scope.headerCount = 0;
$scope.headers = new Array("Id", "Name", "URL", "Description");
$scope.fetchAllSamples = function() {
$scope.response = null;
$scope.method = 'GET';
$scope.url = '/api/samples';
$http({
method: $scope.method,
url: $scope.url
}).then(function(response) {
$scope.data = response.data;
angular.forEach(response.data,function(value,key) {
$scope.sampleCount += 1;
});
},
function(response) {
$scope.data = response.data || "Request failed";
}
);
};
$scope.createSample = function() {
$scope.response = null;
$scope.method = 'POST';
$scope.url = '/api/samples';
$http({
method: $scope.method,
url: $scope.url,
data: JSON.stringify({
name: $scope.newSampleName.sampleName,
attributes: $scope.attributes
})
}).then(function(response) {
$scope.fetchAllSamples();
});
};
$scope.fetchAllSamples();
$scope.filteredTodos = [], $scope.currentPage = 1, $scope.numPerPage = 10, $scope.maxSize = 5;
$scope.$watch('currentPage + numPerPage', function() {
var begin = (($scope.currentPage - 1) * $scope.numPerPage),
end = begin + $scope.numPerPage;
$scope.filteredTodos = $scope.data.slice(begin, end);
});
}]);
Some what new to the MEAN stack. Currently I'm reworking an small app I did through codeschool to be full MEAN stack.
The app created can be seen here
Code School app
In rewriting the app using the MEAN stack after submitting the form I must refresh the page to see the city added to the list. What do I need to fix so I don't need to refresh the page for the new Item to be added to the list?
If I'm missing any relevant code below here is my git hub link
git hub link
Here is my code:
angular.module('Cityapp').controller('CityIndexController', function(City, $scope){
$scope.cities = City.query();
window.sc = $scope;
});
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
console.log($scope.city);
console.log(data);
console.log($scope.city);
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
<form ng-controller="CityCreateController">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="saveCity(city)"/>
</form>
<ul ng-controller="CityIndexController" class="city-list">
<li ng-repeat="city in cities">
<a href="#">
{{city.city}}</a></li>
</ul>
It should looks something like that
;(function() {
function Cities($http) {
function City() {
}
City.prototype.save = function() {
return $http.post('/api/city', this);
};
City.cities = [];
City.add = function(city) {
city.save().then(function() {
City.cities.push(city);
});
};
City.getAll = function() {
$http.get('/api/cities').then(function(response) {
City.cities = response.data.map(function(data) {
return new City(data);
});
return cities;
});
};
return City;
}
function CityCreateController(Cities) {
var mv = this;
mv.city = new Cities();
mv.saveCity = function() {
Cities.add(mv.city);
};
}
function CityIndexController($scope, Cities) {
var mv = this;
$scope.$watchCollection(function() {
return Cities.cities;
}, function(cities) {
mv.cities = cities || [];
});
Cities.getAll();
}
angular
.module('app', [])
.factory('Cities', ['$http', Cities])
.controller('CityCreateController', ['Cities', CityCreateController])
.controller('CityIndexController', ['$scope', 'Cities', CityIndexController]);
})();
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<meta charset="utf-8">
</head>
<body ng-app="app">
<form ng-controller="CityCreateController as mv">
<legend> New City</legend>
<input for="City-group" name="City" id="City" type="text" ng-model="mv.city.city" placeholder="City Name">
<input for="City-group" name="desc" id="desc" type="text" ng-model="mv.city.desc" placeholder="Description">
<input type="submit" class="btn btn-default" ng-click="mv.saveCity()"/>
</form>
<ul ng-controller="CityIndexController as mv" class="city-list">
<li ng-repeat="city in mv.cities">
<a href="#">
{{city.city}}</a></li>
</ul>
</body>
</html>
Found a simple fix
angular.module('Cityapp').controller('CityCreateController', function(City, $scope, $http){
$scope.cities = City.query();
$scope.city = new City();
$scope.saveCity = function(city){
$http({
method: 'POST',
url: '/city',
data: city})
.success( function(data, status, headers, config){
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
}).
error(function(data,status,headers,config){
jQuery('.alert').show();
console.log('nope');
});
};
});
Just added the
$scope.cities.push({city: $scope.city.city,
desc: $scope.city.desc});
to the .success. Works like it should. Now on to my next issue.