Assigning response data into an array (angularjs) - angularjs

I am new to angular js, i wanted to assign the suncorp data which is equal to response into an array , what's wrong with the code? . is the result an array of data? . btw dont worry about the services its working the data is from an api (https://jobs.search.gov/jobs/search.json?query=nursing+jobs).
function TESTController($scope, testFac) {
/* console.log("TESTControlleris now available.");*/
$scope.data1= [];
testFac.getData().then(function(response) {
$scope.data1 = response.data;
console.log("Data:",$scope.data1);
})

if response.data is not an array, and you want the data in an array then, you need to push data to array using array push method;
function TESTController($scope, testFac) {
/* console.log("TESTControlleris now available.");*/
$scope.data1= [];
testFac.getData().then(function(response) {
$scope.data1.push(response.data);
console.log("Data:",$scope.data1);
})

var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
var url = 'https://reqres.in/api/products';
$http.get(url).then(
function(response) {
$scope.projects = response.data.data;
},
function error(response) {
$scope.postResultMessage = "Error with status: "
+ response.statusText;
});
}
$scope.getAllProjects();
});
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
</head>
<body ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
<div class="form-group">
<label class="control-label col-sm-2" for="project">Project:</label>
<div class="col-sm-5">
<select id="projectSelector" class="form-control">
<option id="id" ng-repeat="project in projects"
value="{{project.id}}">{{project.name}}</option>
</select>
</div>
</div>
</div>
</div>
</body>
</html>

Related

How to dynamically call data from an API when option is selected

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>

How to modify service url paramer in angularjs

I'm trying to modify the city parameter by searching for a city parameter, but I don't think it's possible to modify an angular service that way. So how would I be able to modify the service parameter in the controller? Any help would be amazing!
HTML:
<section ng-controller="MainController">
<form action="" class="form-inline well well-sm clearfix" >
<span class="glyphicon glyphicon-search"></span>
<input type="text" placeholder="Search..." class="form-control" ng-model="city" />
<button class="btn btn-warning pull-right" ng-click="search()"><strong>Search</strong></button>
</form>
<h1>{{fiveDay.city.name}}</h1>
<div ng-repeat="day in fiveDay.list" class="forecast">
<div class="day">
<div class="weekday">
<p>{{ day.dt*1000 | date}}</p>
<!-- <p>{{ parseJsonDate(day.dt)}}</p> -->
</div>
<div class="weather"><img ng-src="http://openweathermap.org/img/w/{{day.weather[0].icon}}.png"/></div>
<div class="temp">{{day.weather[0].description}}</div>
<div class="temp">Max {{ day.main.temp_max }}°</div>
<div class="temp">Min {{ day.main.temp_min }}°</div>
</div>
</div>
</section>
JS:
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
forecast.city="orlando";
forecast.success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var city = "orlando";
var key="a1f2d85f6babd3bf7afd83350bc5f2a6";
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5')
.success(function(data) {
return data;
})
.error(function(err) {
return err;
});
}]);
City is a variable part in your forecast factory so need to pass it as an argument in function will be the recommended for you
Try this
var app = angular.module('App', []);
app.controller('MainController', ['$scope', 'forecast', function($scope, forecast) {
var city = "orlando";
forecast.getWeatner(city).success(function(data) {
$scope.fiveDay = data;
});
}]);
app.factory('forecast', ['$http', function($http) {
var key = "a1f2d85f6babd3bf7afd83350bc5f2a6";
return {
getWeatner: function(city) {
return $http.get('http://api.openweathermap.org/data/2.5/forecast?q=' + city + '&APPID=' + key + '&units=metric&cnt=5');
}
}
}]);
增加参数 callback , 回调:JSON_CALLBACK
$http.jsonp("http://api.openweathermap.org/data/2.5/forecast?q='+city+'&APPID='+key+'&units=metric&cnt=5&callback=JSON_CALLBACK").success(function(data){ ... });

Passing data from one page to another in angular js

How do I pass data from one page to another in angular js?
I have heard about using something as services but I am not sure how to use it!
Given below is the functionality I want to execute!
On page 1:
<div class="container" ng-controller="mycontrl">
<label for="singleSelect"> Select Date </label><br>
<select nAMe="singleSelect" ng-model="dateSelect">
<option value="2/01/2015">2nd Jan</option>
<option value="3/01/2015">3rd Jan</option>
</select>
<br>
Selected date = {{dateSelect}}
<br/><br/><br/>
<label for="singleSelect"> Select time </label><br>
<select nAMe="singleSelect" ng-model="timeSelect">
<option value="9/10">9AM-10AM</option>
<option value="10/11">10AM-11AM</option>
<option value="11/12">11AM-12PM</option>
<option value="12/13">12PM-1PM</option>
<option value="13/14">1PM-2PM</option>
</select>
<button ng-click="check()">Check!</button>
<br>
Selected Time = {{timeSelect}}
<br/><br/>
User selects time and date and that is used to make call to the db and results are stored in a variable array!
Page 1 controller:
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
Now how do I send this variable $scope.therapist_list which is an array to next page which will be having a different controller and also if services is use how do define it in my application.js file
application.js:
var firstpage=angular.module('firstpage', []);
var secondpage=angular.module('secondpage', []);
To save the data that you want to transfer to another $scope or saved during the routing, you can use the services (Service). Since the service is a singleton, you can use it to store and share data.
Look at the example of jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope,NewsService) {
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{theme:"This is one new"}, {theme:"This is two new"}, {theme:"This is three new"}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
</div>
</body>
UPDATED
Showing using variable in different controller jsfiddle.
var myApp = angular.module("myApp", []);
myApp.controller("ExampleOneController", function($scope, NewsService) {
$scope.newVar = {
val: ""
};
NewsService.newVar = $scope.newVar;
$scope.news = NewsService.news;
});
myApp.controller("ExampleTwoController", function($scope, NewsService) {
$scope.anotherVar = NewsService.newVar;
$scope.news = NewsService.news;
});
myApp.service("NewsService", function() {
return {
news: [{
theme: "This is one new"
}, {
theme: "This is two new"
}, {
theme: "This is three new"
}]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="ExampleOneController">
<h2>
ExampleOneController
</h2>
<div ng-repeat="n in news">
<textarea ng-model="n.theme"></textarea>
</div>
<input ng-model="newVar.val">
</div>
<div ng-controller="ExampleTwoController">
<h2>
ExampleTwoController
</h2>
<div ng-repeat="n in news">
<div>{{n.theme}}</div>
</div>
<pre>newVar from ExampleOneController {{anotherVar.val}}</pre>
</div>
</body>
OK,
you write a another module ewith factory service e.g.
angular
.module('dataApp')
.factory('dataService', factory);
factory.$inject = ['$http', '$rootScope', '$q', '$log'];
function factory($http, $rootScope,$q,$log) {
var service = {
list: getList
};
service.therapist_list = null;
return service;
function getList() {
var config= {
params: {
time: times,
date:dates
}
};
$http.get('/era',config).success(function(response) {
console.log("I got the data I requested");
$scope.therapist_list = response;
});
$log.debug("get Students service");
$http.get('/era',config).then(function successCallback(response) {
service.therapist_list = response.data;
$log.debug(response.data);
}, function errorCallback(response) {
$log.debug("error" + response);
});
}
}
Add this module as dependencies to your both page apps like
var firstpage=angular.module('firstpage', [dataApp]);
var secondpage=angular.module('secondpage', [dataApp]);
and then in your controller consume that service
.controller('homeController', ['$scope', 'dataService', function ($scope, dataService) {
}]);

Array not returning in angularstrap typeahead

I'm following this plunker to create a typeahead in my project.
http://plnkr.co/edit/ZjpJxXkl0v5LhQdxcqWn?p=preview
app.js (not working with my API)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
return res.data.results;
});
};
Index.html
<!-- Using an async data provider -->
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small></label>
<input
type="text"
class="form-control"
ng-model="selectedAddress"
data-animation="am-flip-x"
ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)"
placeholder="Enter address"
bs-typeahead>
</div>
Inn my case i'm fetching data from a .net API. When i console log the results from the API I can see the array is returning from the API. but when i try to return it to the typeahead the data isn't displayed. however if i try to create an array of mock objects and then manually insert the data into the array aswell the results appear in the typeahead.
app.js (data is displayed)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
[{formatted_address: "Alabama"},{formatted_address: "Arkansas"},{formatted_address: res.data.results[0]}]
return res.data.results;
});
};
why could this be happening and how would i fix it?
I can't see your full solution so it's difficult to say what did you missed but please see below for working solution.
var app = angular.module('app', ['mgcrea.ngStrap']);
app.controller('firstCtrl', function($scope, $http) {
$scope.getAddress = function(viewValue) {
var params = {
address: viewValue,
sensor: false
};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: params
})
.then(function(res) {
return res.data.results;
});
};
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.js" data-semver="v2.1.3"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.tpl.js" data-semver="v2.1.3"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small>
</label>
<input type="text" class="form-control" ng-model="selectedAddress" data-animation="am-flip-x" ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)" placeholder="Enter address" bs-typeahead>
</div>
</div>
</body>

ng-repeat not updating the list when adding data

my problem is that the ng-repeat is not updating automatically the data. When I press add pin in my code, the element is added correctly to the database. If I reload the page the data appear correctly, but not as angular should.
For the record, the Update and delete are working correctly.
Thanks in advance
This is my app.js code:
var app = angular.module("app", []);
app.controller("AppCtrl", function ($http) {
var app = this;
$http.get("/api/pin").success(function (data) {
app.pins = data.objects;
})
app.addPin = function (scope) {
$http.post("/api/pin", {"title":"new", "image":"http://placekitten.com/200/200/?image=" + app.pins.length})
.success(function(data) {
add.pins.push(data);
})
}
app.deletePin = function (pin) {
$http.delete("/api/pin/" + pin.id).success(function(response) {
app.pins.splice(app.pins.indexOf(pin), 1)
})
}
app.updatePin = function (pin) {
$http.put("/api/pin/" + pin.id, pin);
}
})
This is my index.html file:
<html>
<head>
<title>Pin Clone</title>
<script src="angular/angular.js"></script>
<script src="angular/angular-resource.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<button ng-click="app.addPin()">Add Pin</button>
<div ng-repeat="pin in app.pins">
<img ng-src="{{ pin.image }}" alt=""/>
<div class="ui">
<input type="text" ng-model="pin.title"/>
<button ng-click="app.updatePin(pin)">Update</button>
<button ng-click="app.deletePin(pin)">Delete</button>
</div>
</div>
</body>
</html>
First of all, you should really use $scope (Doc) in your controller. You can read more about the differences in this post.
Thus your controller would look like this.
app.controller("AppCtrl", ["$scope", "$http",
function ($scope, $http) {
$http.get("/api/pin").success(function (data) {
$scope.pins = data.objects;
});
$scope.addPin = function () {
....
};
$scope.deletePin = function (pin) {
....
};
$scope.updatePin = function (pin) {
....
};
}]);
HTML:
<body ng-app="app" ng-controller="AppCtrl">
<button ng-click="addPin()">Add Pin</button>
<div ng-repeat="pin in pins">
<img ng-src="{{ pin.image }}" alt=""/>
<div class="ui">
<input type="text" ng-model="pin.title"/>
<button ng-click="updatePin(pin)">Update</button>
<button ng-click="deletePin(pin)">Delete</button>
</div>
</div>
</body>
Finally, here comes the core part. You should call $apply (Doc) when your models change. You can read more in this blog post.
$http
.post("/api/pin", {
title: "new",
image:
"http://placekitten.com/200/200/?image="
+ $scope.pins.length
})
.success(function(data) {
$scope.$apply(function() {
$scope.pins.push(data);
});
});
Thus, the full controller code:
app.controller("AppCtrl", ["$scope", "$http",
function ($scope, $http) {
$http.get("/api/pin").success(function (data) {
$scope.pins = data.objects;
});
$scope.addPin = function () {
$http
.post("/api/pin", {
title: "new",
image:
"http://placekitten.com/200/200/?image="
+ $scope.pins.length
})
.success(function(data) {
$scope.$apply(function() {
$scope.pins.push(data);
});
});
};
$scope.deletePin = function (pin) {
$http
.delete("/api/pin/" + pin.id)
.success(function(response) {
$scope.$apply(function() {
$scope.pins.splice(
$scope.pins.indexOf(pin), 1
);
});
});
};
$scope.updatePin = function (pin) {
$http.put("/api/pin/" + pin.id, pin);
};
}]);
Cannot agree with Gavin. First, what you're doing is totally fine. Creating instance of controller is a much better practice than using $scope. Second, $apply() is not needed here.
The problem is ng-repeat created a new scope. While pin is updated, app.pins is not. You should do
var app = angular.module("app", []);
app.controller("AppCtrl", function ($http) {
var app = this;
$http.get("/api/pin").success(function (data) {
app.pins = data.objects;
})
app.addPin = function (scope) {
$http.post("/api/pin", {"title":"new", "image":"http://placekitten.com/200/200/?image=" + app.pins.length})
.success(function(data) {
add.pins.push(data);
})
}
app.deletePin = function (index) {
$http.delete("/api/pin/" + app.pins[index].id).success(function(response) {
app.pins.splice(index, 1)
})
}
app.updatePin = function (index) {
$http.put("/api/pin/" + app.pins[index].id, app.pins[index]);
}
})
and
<html>
<head>
<title>Pin Clone</title>
<script src="angular/angular.js"></script>
<script src="angular/angular-resource.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<button ng-click="app.addPin()">Add Pin</button>
<div ng-repeat="pin in app.pins track by $index">
<img ng-src="{{ pin.image }}" alt=""/>
<div class="ui">
<input type="text" ng-model="pin.title"/>
<button ng-click="app.updatePin($index)">Update</button>
<button ng-click="app.deletePin($index)">Delete</button>
</div>
</div>
</body>
</html>
check here: How to update ng-model on event click using $event in Angularjs
in posted code you've got typo error
app.addPin = function (scope) {
$http.post("/api/pin", {"title":"new", "image":"http://placekitten.com/200/200/?image=" + app.pins.length})
.success(function(data) {
// add.pins.push(data); <--- app not add
app.pins.push(data)
})
}

Resources