This is a basic weather app that grabs info from an open weather API. Upon loading, it gets the weather information for the default city and I'm able to successfully log the returned info to the console, however my view doesn't update until I switch to a different view and then back. I feel like a $scope.$apply needs to go somewhere, but I couldn't get it working anywhere I tried.
App:
var weather = angular.module('weather', ['ngRoute', 'ngResource', 'ui.router']);
weather.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/overview');
$stateProvider
.state('overview', {
url: '/overview',
templateUrl: 'pages/overview.html',
controller: 'overviewController'
})
.state('forecast', {
url: '/forecast',
templateUrl: 'pages/forecast.html'
})
.state('details', {
url: '/details',
templateUrl: 'pages/details.html'
})
});
weather.controller('homeController', ['$scope', '$location', '$resource', 'weatherService', function($scope, $location, $resource, weatherService) {
$scope.txtCity = weatherService.city;
$scope.submit = function() {
weatherService.city = $scope.txtCity;
weatherService.getForecast(weatherService.city, function(x){
weatherService.currentForecast = x;
// TESTING
console.log(x);
});
};
// Run the submit function initially to retrieve weather data for the default city
$scope.submit();
// Function to determine the active tab, sets its class as "active"
$scope.isActive = function (path) {
return ($location.path().substr(0, path.length) === path) ? 'active' : '';
}
}]);
weather.controller('overviewController', ['$scope', '$filter', 'weatherService', function($scope, $filter, weatherService) {
$scope.currentForecast = weatherService.currentForecast;
// Kelvin to Fahrenheit
$scope.convertTemp = function(temp) {
return Math.round((1.8*(temp - 273))+32);
}
$scope.convertToDate = function(dt) {
var date = new Date(dt * 1000);
return ($filter('date')(date, 'EEEE, MMM d, y'));
};
}]);
weather.service('weatherService', function($resource, $http){
this.currentForecast = null;
// default city
this.city = 'Chicago, IL';
this.getForecast = function(location, successcb) {
$http({
method : "GET",
url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
}).success(function(data){
successcb(data);
}).error(function(){
});
}
});
overview.html (view):
<h4>Daily</h4>
<ul>
<li ng-repeat="w in currentForecast.list">{{ convertToDate(w.dt) }} {{ convertTemp(w.temp.day) }}°</li>
</ul>
Submit form:
<form ng-submit="submit()">
<button type="submit" class="btn btn-primary btn-sm">Get Forecast</button>
<input type="text" ng-model="txtCity">
</form>
Change your service function to:
this.getForecast = = function(location) {
return $http({
method : "GET",
url : "http://api.openweathermap.org/data/2.5/forecast/daily?q="+location+"&mode=json&cnt=7&appid=e92f550a676a12835520519a5a2aef4b"
}).then(
function(response) {
return response.data;
}
)
};
And in your controller, use it like this in the submit function:
weatherService.getForecast(weatherService.city).then(
function(data) {
weatherService.currentForecast = data;
console.log(data);
}
);
This allows you to handle the success function of the $http promise directly from the controller. Currently you're passing the function to the service, and it doesn't know what the weatherServiceparameter is, because it outside of the service scope (It's avalable in the controller).
Now, in your overviewController controller, you can watch for changes inside the service like this:
$scope.$watch(function() { return weatherService.currentForecast; },
function(newVal) {
if(!newVal) return;
$scope.currentForecast = newVal;
}, true);
Related
I'm following this tutorial .. First time I execute function (fazerLogin) from ng-click, after set cookies, I don't know why, it is reloading current state before $state.go function. When button activates fazerLogin function(first time only), it executes all the code, but before my $state.go('temperatura'), it "reloads" the same state, executing my function initController() and cleaning all credentials. If I try to login again, it works perfectly. And if I'm logged and I go to state login again, it works, without any of this problem. There is my code
LoginController:
app.controller('LoginController', function($timeout, $rootScope, $location, $scope, $cookies, $state, AuthService){
(function initController() {
AuthService.LimparCredenciais();
})();
$scope.fazerLogin = function () {
if(angular.isUndefined($scope.login)){
swal("Preencha o campo 'Login'");
$('#usuario').focus();
}else if(angular.isUndefined($scope.senha)){
swal("Preencha o campo 'Senha'");
$('#senha').focus();
}else{
$scope.usuario = {login: $scope.login, senha: $scope.senha};
AuthService.Login($scope.usuario, function(response) {
if(response != null) {
if(!response.status){
swal("Login ou senha incorretos!");
}else{
//HERE IS THE PROBLEM THAT IS RELOADING CURRENT PAGE
AuthService.AtualizarCredenciais(response.usuario);
$state.go('temperatura');
}
} else {
swal("ERRO");
}
});
}
};
});
And my app.js:
var app = angular.module('app', [ 'ui.router', 'ui.materialize', 'ngResource', 'angularUtils.directives.dirPagination', 'ngCookies', 'zingchart-angularjs']);
app.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
// $urlRouterProvider.otherwise('login');
$stateProvider.state('login', {
url: "/login",
templateUrl: "pages/login.html",
controller: "LoginController"
})
});
app.run(function($cookies, $rootScope, $location, $state, $cookies, $timeout) {
$rootScope.baseUrl = window.location.origin + window.location.pathname;
// keep user logged in after page refresh
$rootScope.global = $cookies.get('global') || {};
$rootScope.$on('$locationChangeStart', function(event, next, current) {
// redirect to login page if not logged in
if ($location.path() !== '/login' && angular.isUndefined($rootScope.global.usuario)
&& $location.path() !== '/cadastro') {
$state.go('login');
}
});
});
In my AuthService, there is my code:
angular.module("app").factory(
"AuthService",
function(Base64, $http, $cookies, $rootScope, $timeout, Usuario, $state) {
var service = {}
service.Login = function(usuario, callback) {
Usuario.logar(usuario)
.success(function(data) {
callback(data);
}).error(function(erro) {
// $state.go('erro');
});
};
service.AtualizarCredenciais = function(usuario) {
console.log("atualizando credenciais");
var key = Base64.encode(usuario.login + ':' + usuario.senha);
$rootScope.global = {
usuario : {
login : usuario.login,
key : key,
id : usuario.id
}
};
$cookies.put('global', $rootScope.global);
console.log('setou cookies');
//AFTER SET COOKIES, IT IS RELOADING CURRENT STATE AND EXECUTING METHOD TO CLEAR CURRENT CREDENTIALS
};
service.LimparCredenciais = function() {
console.log("limpando credenciais");
$rootScope.global = {};
$cookies.remove('global');
};
return service;
});
In my login.html:
<div class="row">
<div class="input-field col s12">
<a ng-click="fazerLogin()" class="btn waves-effect waves-light col s12">Login</a>
</div>
</div>
In my Usuario.js, there are only posts to my php files to get some data from database.
In my app I have a controller that takes a user input consisting of a twitter handle from one view and passes it along through my controller into my factory where it is sent through to my backend code where some API calls are made and ultimately I want to get an image url returned.
I am able to get the image url back from my server but I have been having a whale of a time trying to append it another view. I've tried messing around with $scope and other different suggestions I've found on here but I still can't get it to work.
I've tried doing different things to try and get the pic to be interpolated into the html view. I've tried injecting $scope and playing around with that and still no dice. I'm trying not to use $scope because from what I understand it is better to not abuse $scope and use instead this and a controller alias (controllerAs) in the view.
I can verify that the promise returned in my controller is the imageUrl that I want to display in my view but I don't know where I'm going wrong.
My controller code:
app.controller('TwitterInputController', ['twitterServices', function (twitterServices) {
this.twitterHandle = null;
// when user submits twitter handle getCandidateMatcPic calls factory function
this.getCandidateMatchPic = function () {
twitterServices.getMatchWithTwitterHandle(this.twitterHandle)
.then(function (pic) {
// this.pic = pic
// console.log(this.pic)
console.log('AHA heres the picUrl:', pic);
return this.pic;
});
};
}]);
Here is my factory code:
app.factory('twitterServices', function ($http) {
var getMatchWithTwitterHandle = function (twitterHandle) {
return $http({
method: 'GET',
url: '/api/twitter/' + twitterHandle
})
.then(function (response) {
return response.data.imageUrl;
});
};
return {
getMatchWithTwitterHandle: getMatchWithTwitterHandle,
};
});
this is my app.js
var app = angular.module('druthers', ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/', {
url: '/',
templateUrl: 'index.html',
controller: 'IndexController',
controllerAs: 'index',
views: {
'twitter-input': {
templateUrl: 'app/views/twitter-input.html',
controller: 'TwitterInputController',
controllerAs: 'twitterCtrl'
},
'candidate-pic': {
templateUrl: 'app/views/candidate-pic.html',
controller: 'TwitterInputController',
controllerAs: 'twitterCtrl'
}
}
});
});
Here is the view where I want to append the returned image url
<div class="col-md-8">
<img class="featurette-image img-circle" ng-src="{{twitterCtrl.pic}}"/>
</div>
You can do as
app.controller('TwitterInputController', ['twitterServices', function (twitterServices) {
this.twitterHandle = null;
// added
this.pic = '';
// when user submits twitter handle getCandidateMatcPic calls factory function
this.getCandidateMatchPic = function () {
twitterServices.getMatchWithTwitterHandle(this.twitterHandle)
.then(function (pic) {
// this.pic = pic
// console.log(this.pic)
console.log('AHA heres the picUrl:', pic);
return this.pic;
});
};
}]);
html
<div class="col-md-8">
<div ng-controller='TwitterInputController as twitterCtrl'>
<img class="featurette-image img-circle" ng-src="{{twitterCtrl.pic}}"/>
</div>
</div>
hope this may help you
Here is working demo http://jsfiddle.net/r904fnb3/2/
angular.module('myapp', []).controller('ctrl', function($scope, $q){
var vm = this;
vm.image = '';
vm.setUrl = function(){
var deffered = $q.defer();
setTimeout(function(){
deffered.resolve('https://angularjs.org/img/AngularJS-large.png');
}, 3000);
//promise
deffered.promise.then(function(res){
console.log(res);
vm.image = res;
});
};
});
hope this may help you
I already write a code to display a loader div, when any resources is in pending, no matter it's getting via $http.get or routing \ ng-view.
I wan't only information if i'm going bad...
flowHandler service:
app.service('flowHandler', function(){
var count = 0;
this.init = function() { count++ };
this.end = function() { count-- };
this.take = function() { return count };
});
The MainCTRL append into <body ng-controller="MainCTRL">
app.controller("MainCTRL", function($scope, flowHandler){
var _this = this;
$scope.pageTitle = "MainCTRL";
$scope.menu = [];
$scope.loader = flowHandler.take();
$scope.$on("$routeChangeStart", function (event, next, current) {
flowHandler.init();
});
$scope.$on("$routeChangeSuccess", function (event, next, current) {
flowHandler.end();
});
updateLoader = function () {
$scope.$apply(function(){
$scope.loader = flowHandler.take();
});
};
setInterval(updateLoader, 100);
});
And some test controller when getting a data via $http.get:
app.controller("BodyCTRL", function($scope, $routeParams, $http, flowHandler){
var _this = this;
$scope.test = "git";
flowHandler.init();
$http.get('api/menu.php').then(function(data) {
flowHandler.end();
$scope.$parent.menu = data.data;
},function(error){flowHandler.end();});
});
now, I already inject flowHandler service to any controller, and init or end a flow.
It's good idea or its so freak bad ?
Any advice ? How you do it ?
You could easily implement something neat using e.g. any of Bootstrap's progressbars.
Let's say all your services returns promises.
// userService ($q)
app.factory('userService', function ($q) {
var user = {};
user.getUser = function () {
return $q.when("meh");
};
return user;
});
// roleService ($resource)
// not really a promise but you can access it using $promise, close-enough :)
app.factory('roleService', function ($resource) {
return $resource('role.json', {}, {
query: { method: 'GET' }
});
});
// ipService ($http)
app.factory('ipService', function ($http) {
return {
get: function () {
return $http.get('http://www.telize.com/jsonip');
}
};
});
Then you could apply $scope variable (let's say "loading") in your controller, that is changed when all your chained promises are resolved.
app.controller('MainCtrl', function ($scope, userService, roleService, ipService) {
_.extend($scope, {
loading: false,
data: { user: null, role: null, ip: null}
});
// Initiliaze scope data
function initialize() {
// signal we are retrieving data
$scope.loading = true;
// get user
userService.getUser().then(function (data) {
$scope.data.user = data;
// then apply role
}).then(roleService.query().$promise.then(function (data) {
$scope.data.role = data.role;
// and get user's ip
}).then(ipService.get).then(function (response) {
$scope.data.ip = response.data.ip;
// signal load complete
}).finally(function () {
$scope.loading = false;
}));
}
initialize();
$scope.refresh = function () {
initialize();
};
});
Then your template could look like.
<body ng-controller="MainCtrl">
<h3>Loading indicator example, using promises</h3>
<div ng-show="loading" class="progress">
<div class="progress-bar progress-bar-striped active" style="width: 100%">
Loading, please wait...
</div>
</div>
<div ng-show="!loading">
<div>User: {{ data.user }}, {{ data.role }}</div>
<div>IP: {{ data.ip }}</div>
<br>
<button class="button" ng-click="refresh();">Refresh</button>
</div>
This gives you two "states", one for loading...
...and other for all-complete.
Of course this is not a "real world example" but maybe something to consider. You could also refactor this "loading bar" into it's own directive, which you could then use easily in templates, e.g.
//Usage: <loading-indicator is-loading="{{ loading }}"></loading-indicator>
/* loading indicator */
app.directive('loadingIndicator', function () {
return {
restrict: 'E',
scope: {
isLoading: '#'
},
link: function (scope) {
scope.$watch('isLoading', function (val) {
scope.isLoading = val;
});
},
template: '<div ng-show="isLoading" class="progress">' +
' <div class="progress-bar progress-bar-striped active" style="width: 100%">' +
' Loading, please wait...' +
' </div>' +
'</div>'
};
});
Related plunker here http://plnkr.co/edit/yMswXU
I suggest you to take a look at $http's pendingRequest propertie
https://docs.angularjs.org/api/ng/service/$http
As the name says, its an array of requests still pending. So you can iterate this array watching for an specific URL and return true if it is still pending.
Then you could have a div showing a loading bar with a ng-show attribute that watches this function
I would also encapsulate this requests in a Factory or Service so my code would look like this:
//Service that handles requests
angular.module('myApp')
.factory('MyService', ['$http', function($http){
var Service = {};
Service.requestingSomeURL = function(){
for (var i = http.pendingRequests.length - 1; i >= 0; i--) {
if($http.pendingRequests[i].url === ('/someURL')) return true;
}
return false;
}
return Service;
}]);
//Controller
angular.module('myApp')
.controller('MainCtrl', ['$scope', 'MyService', function($scope, MyService){
$scope.pendingRequests = function(){
return MyService.requestingSomeURL();
}
}]);
And the HTML would be like
<div ng-show="pendingRequests()">
<div ng-include="'views/includes/loading.html'"></div>
</div>
I'd check out this project:
http://chieffancypants.github.io/angular-loading-bar/
It auto injects itself to watch $http calls and will display whenever they are happening. If you don't want to use it, you can at least look at its code to see how it works.
Its very simple and very useful :)
I used a base controller approach and it seems most simple from what i saw so far. Create a base controller:
angular.module('app')
.controller('BaseGenericCtrl', function ($http, $scope) {
$scope.$watch(function () {
return $http.pendingRequests.length;
}, function () {
var requestLength = $http.pendingRequests.length;
if (requestLength > 0)
$scope.loading = true;
else
$scope.loading = false;
});
});
Inject it into a controller
angular.extend(vm, $controller('BaseGenericCtrl', { $scope: $scope }));
I am actually also using error handling and adding authorization header using intercepting $httpProvider similar to this, and in this case you can use loading on rootScope
I used a simpler approach:
var controllers = angular.module('Controllers', []);
controllers.controller('ProjectListCtrl', [ '$scope', 'Project',
function($scope, Project) {
$scope.projects_loading = true;
$scope.projects = Project.query(function() {
$scope.projects_loading = false;
});
}]);
Where Project is a resource:
var Services = angular.module('Services', [ 'ngResource' ]);
Services.factory('Project', [ '$resource', function($resource) {
return $resource('../service/projects/:projectId.json', {}, {
query : {
method : 'GET',
params : {
projectId : '#id'
},
isArray : true
}
});
} ]);
And on the page I just included:
<a ng-show="projects_loading">Loading...</a>
<a ng-show="!projects_loading" ng-repeat="project in projects">
{{project.name}}
</a>
I guess, this way, there is no need to override the $promise of the resource
I'm storing data and language terms for the website with json, and depending on the language selected i load the adequate file. The problem is when i switch the language, only the adress in the adressbar change without reloading the right json file.
factory.js
app.factory('PostsFactory', function ($http, $q, $timeout) {
var factory = {
posts: false,
find: function (lang) {
var deferred = $q.defer();
if (factory.posts !== false) {
deferred.resolve(factory.posts);
} else {
$http.get(lang+'/json.js').success(function (data, status) {
factory.posts = data;
$timeout(function () {
deferred.resolve(factory.posts);
})
}).error(function (data, status) {
deferred.reject('error')
});
}
return deferred.promise;
},
get: function (id, lang) {
var deferred = $q.defer();
var post = {};
var posts = factory.find(lang).then(function (posts) {
angular.forEach(posts, function (value, key) {
if (value.id == id) {
post = value;
};
});
deferred.resolve(post);
}, function (msg) {
deferred.reject(msg);
})
return deferred.promise;
}
}
return factory;
})
controller
posts.js
app.controller('PostsCtrl', function ($scope, PostsFactory, $rootScope, $routeParams) {
$rootScope.loading = true;
lang = $routeParams.lang;
PostsFactory.find(lang).then(function (posts) {
$rootScope.loading = false;
$scope.posts = posts;
}, function (msg) {
alert(msg);
});
});
post.js
app.controller('PostCtrl', function ($scope, PostsFactory, $routeParams, $rootScope) {
$rootScope.loading = true;
SounanFactory.get($routeParams.id, $routeParams.lang).then(function (post) {
$rootScope.loading = false;
$scope.title = post.title;
$scope.text = post.text;
$scope.image = post.image;
$scope.id = post.id;
}, function (msg) {
alert(msg);
});
});
app.js
var app = angular.module('Posts', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider.when('/:lang/', {
templateUrl: 'partials/posts.html', controller: 'PostsCtrl'})
.when('/:lang/post/:id', {
templateUrl: 'partials/post.html', controller: 'PostCtrl'})
.otherwise({
redirectTo: '/en'
});
})
posts.html
<div ng-hide="loading">
<a href="#/en/post/{{post.id}}" ng-repeat="post in posts " class="{{post.class}}">
<div class="title">{{post.title}}</div>
<div class="index">{{post.id}}</div>
</a>
</div>
index.html
<body ng-app="Posts">
<div ng-show="loading">Loading ...</div>
<div class="container" ng-view></div>
<a href="#/fr" >FR</a>
<a href="#/en" >EN</a>
</body>
In your posts.js have you tried adding $scope.$apply() underneath $scope.posts = posts; in posts.js and again under $scope.id = post.id; in post.js?
The problem that you're facing is probably due to Angular's digest cycle and the bizarre way you're trying to pass values around through promises/objects/wizardry.
I mean, it's kind of the least of your worries. I know nothing of the project but there are a few things that could be causing an issue here.
Why do you have a $timeout() without a time?
Why are you setting a lang var and then immediately using it instead of just passing it through?
Why are you assigning a posts member of your factory and then using it immediately instead of just passing it through?
You should be using ng-href for dynamic url's
Let us know how you get on.
I am fairly new to Angular and I find it quite difficult to think the Angular way.
I have registered a SessionService which loads a user object at login. Each controller can depend on the SessionService so I can have some sort of access control.
app.factory('SessionService',['$resource', function($resource){
var service = $resource('/session/:param',{},{
'login': {
method: 'POST'
}
});
var _user = { authorized: false };
function getUser() {
return _user;
}
function authorized(){
return _user.authorized === true;
}
function unauthorized(){
return _user.authorized === false;
}
function login(newUser,resultHandler) {
service.login(
newUser,
function(res){
_user = (res.user || {});
_user.authorized = res.authorized;
if(angular.isFunction(resultHandler)) {
resultHandler(res);
}
}
);
}
return {
login: login,
authorized: authorized,
getUser: getUser
};
}]);
...this is how I access the SessionService from a controller:
app.controller('SidebarCtrl', ['$scope', 'SessionService', function($scope, SessionService) {
$scope.template = '/templates/sidebar/public.html';
if(SessionService.authorized()){
$scope.template = '/templates/sidebar/menu.html'; // <-- ???
}
}]);
...and here the html file:
<div ng-controller="SidebarCtrl">
<div ng-include src="template"></div>
</div>
Here is my question: How do I make the SidebarCtrl's template dependent on SessionService.authorize? So the sidebar shows the right content according to a user being logged in or not.
I hope this makes sense to you.
You need to $watch the SessionService.authorized(). So change the controller as:
app.controller('SidebarCtrl', ['$scope', 'SessionService', function($scope, SessionService) {
$scope.template = null;
$scope.$watch(
function() {
return SessionService.authorized();
},
function(authorized) {
if( authorized ) $scope.template = '/templates/sidebar/menu.html';
else $scope.template = '/templates/sidebar/public.html';
}
);
}]);