Angular values do not reflect in scope until view changes - javascript

Below is my HTML code :
<div class="container-fluid">
<div class="jumbotron" id="welcomehead">
<br><br><br><br><br><br><br><br><br><br>
</div>
<div class="row">
<div class="col-md-12">
<h2>Welcome {{username }}, your Season total is {{total }}</h2>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3 id="slogan" >5 teams; 1 Goal</h3><br>
<img src="http://res.cloudinary.com/deji/image/upload/v1508887997/ymkit_ww8np1.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508888352/indkit_zop1gx.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508887290/chad2kit_fa3lrh.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508887718/fbg2kit_lzndap.jpg">
<img src="http://res.cloudinary.com/deji/image/upload/v1508888206/vgc_kit_hvpdz4.jpg">
</div>
</div>
Below is the javascript code for the html code:
'use strict';
angular.module('TNF.welcome', ['ngRoute', 'firebase'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/welcome',{
templateUrl:'welcome/welcome.html',
controller: 'WelcomeCtrl'
});
}])
.controller('WelcomeCtrl',['$scope','$firebaseAuth','CommonProp','$location','DatabaseService',
function($scope,$firebaseAuth, CommonProp,$location, databaseService){
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
databaseService.users.child(user.uid).once('value', function(usersSnapshot){
var users = usersSnapshot.val();
var total = users.total;
$scope.username = user.email;
$scope.total = total;
}, function(err) {
console.log(err);
$scope.total = 0;
});
} else {
// No user is signed in.
$location.path('/home');
}
});
$scope.logout = function(){
firebase.auth().signOut().then(function() {
console.log('Signed Out');
$location.path('/home');
}, function(error) {
console.error('Sign Out Error', error);
});
};
MY Issue
My issue is that the {{username}} and {{total}} values, which are results of the firebase query do not show in the view once the page loads. However, the values show up once I leave the page and then return to the view. Does this mean that the HTML code loads faster than the firebase query can be resolved? If so, is there a way to make the page only load AFTER the firebase query is resolved?

you'll need to let angular know to run an update.
$scope.username = user.email;
$scope.total = total;
$scope.$apply();

Related

Angular not updating page after http request (scope issue?)

When my page loads, all the items in my mongo db are displayed. I have a form to input new entries, or delete entries. When creating or deleting, the http process works, but the new data is not updated in the DOM.
Most of the related questions I have researched suggest to make sure my ng-controller wraps the entire body, which it does. Other's suggest to use $apply, but I've also read that this is wrong. When I try it, I am alerted "in progress" anyway.
My only guess is that after the http request, a new scope is loaded and angular doesn't pick up on that. Or for some reason its just not reloading the data after my request. Here is my code, thanks for your help.
index.html
<body ng-controller="MainController">
<!-- list records and delete checkbox -->
<div id="record-list" class="row">
<div class="col-sm-4 col-sm-offset-4">
<!-- loop over records in $scope.records -->
<div class="checkbox" ng-repeat="record in records">
<label>
<input type="checkbox" ng-click="deleteRecord(record._id)">
{{ record.artist}} - {{ record.album }} - {{ record.bpm}}
</label>
</div>
</div>
</div>
<!-- record form data -->
<div id="record-form" class="row">
<div class="col-sm-8 col-sm-offset-2 text-center">
<form>
<div class="form-group">
<input type="artist" class="form-control input-lg text-center" placeholder="Artist" ng-model="formData.artist">
</div>
<div class="form-group">
<input type="album" class="form-control input-lg text-center" placeholder="Album" ng-model="formData.album">
</div>
<div class="form-group">
<input type="bpm" class="form-control input-lg text-center" placeholder="BPM" ng-model="formData.bpm">
</div>
<button type="submit" class="btn btn-primary btn-lg" ng-click="createRecord()">Add</button>
</form>
</div>
</div>
</div>
controller.js
angular.module('myApp', []).controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.sortType = 'artist';
$scope.sortReverse = false;
//$scope.searchRecords = '';
$http.get('/api/records/')
.success(function(data) {
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createRecord = function() {
$http.post('/api/records/', $scope.formData)
.success(function(data) {
//$scope.formData = {};
$scope.records = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
$scope.deleteRecord = function(id) {
$http.delete('/api/records/' + id)
.success(function(data) {
$scope.records = data;
console.log("delete record scope: " + data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}])
Your controller JS looks fine - I would say from looking at this that you need to export the updated values from your mongoDB collection when the POST/DELETE is successful.
If you use Mongoose (mongoDB plugin), you can update your API code to send back the updated data upon success with something like this:
// POST
// --------------------------------------------------------
// Provides method for saving new record to the db, then send back list of all records
app.post('/api/records', (req, res) => {
// Creates a new record based on the Mongoose Schema
const newRecord= new Record(req.body);
// New record is saved to the db
newRecord.save((err) => {
// Test for errors
if(err) res.send(err);
// Now grab ALL data on records
const all = Records.find({});
all.exec((err, records) => {
// Test for errors
if(err) res.send(err);
// If no errors are found, it responds with JSON for all records
res.json(records);
});
});
});

Angularjs : Print object from control to view with ionic

I try to build new APP with ionic framework and Angularjs.
Now my problem is i cannot show the result from controller to view. I try open console.log(allposts); in my browser ans we show the result good.
But in view its not show any thing
allpost.html
<dive class="item itemfull" ng-repeat="post in allpost">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news"><div class="title" ng-bind-html="post.content"></div></div>
</div>
</div>
</div>
And the controller
myApp.controller('allpost', function($scope , $http , $stateParams , Allposts) {
var id = $stateParams.id;
$scope.post = Allposts.GetAllposts(id);
});
myApp.factory('Allposts',['$http', '$q',function($http,$q){
var allposts = [];
var pages = null;
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id="+id+"&status=publish",{params: null}).then(function (response) {
items = response.data.posts;
allposts = items;
console.log(allposts);
return items;
$ionicLoading.hide();
});
}
}
}]);
Where is error ?
try to change the code like this in controller and factory in js files
.controller('allpost', function ($scope, $http, $stateParams, Allposts) {
var id = $stateParams.id;
Allposts.GetAllposts(id).then(
function (response) {
$scope.allPosts = response.data.posts;
});
})
.factory('Allposts', ['$http', '$q', function ($http, $q) {
return {
GetAllposts: function (id) {
return $http.get("http://kotshgfx.info/azkarserv/?json=get_category_posts&id=" +
id + "&status=publish");
}
}
}]);
the html file
<div class="item itemfull" ng-repeat="post in allPosts">
<div class="item item-body">
<div>{{ post.title }}
<div class="title-news">
<div class="title" ng-bind-html="post.content"></div>
</div>
</div>
</div>
</div>
It works for my test

content is loading everytime I refresh the page

I'm developing a simple CRUD application with MEAN stack. So the scenario is a user post a data to the server and it will render the data in real-time. Everything works fine but whenever I refresh the page ,
It will sort of loads all the content, every time it tries to fetch the data. I guess this is a caching problem.
So what I want to achieve is, every time a user refresh the page or go to another link, the content will be there without waiting for split seconds.
Here's the link to test it on, try to refresh the page
https://user-testing2015.herokuapp.com/allStories
and the code
controller.js
// start our angular module and inject our dependecies
angular.module('storyCtrl', ['storyService'])
.controller('StoryController', function(Story, $routeParams, socketio) {
var vm = this;
vm.stories = [];
Story.all()
.success(function(data) {
vm.stories = data;
});
Story.getSingleStory($routeParams.story_id)
.success(function(data) {
vm.storyData = data;
});
vm.createStory = function() {
vm.message = '';
Story.create(vm.storyData)
.success(function(data) {
// clear the form
vm.storyData = {}
vm.message = data.message;
});
};
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
.controller('AllStoryController', function(Story, socketio) {
var vm = this;
Story.allStories()
.success(function(data) {
vm.stories = data;
});
socketio.on('story', function (data) {
vm.stories.push(data);
});
})
service.js
angular.module('storyService', [])
.factory('Story', function($http, $window) {
// get all approach
var storyFactory = {};
var generateReq = function(method, url, data) {
var req = {
method: method,
url: url,
headers: {
'x-access-token': $window.localStorage.getItem('token')
},
cache: false
}
if(method === 'POST') {
req.data = data;
}
return req;
};
storyFactory.all = function() {
return $http(generateReq('GET', '/api/'));
};
storyFactory.create = function(storyData) {
return $http(generateReq('POST', '/api/', storyData));
};
storyFactory.getSingleStory = function(story_id) {
return $http(generateReq('GET', '/api/' + story_id));
};
storyFactory.allStories = function() {
return $http(generateReq('GET', '/api/all_stories'));
};
return storyFactory;
})
.factory('socketio', ['$rootScope', function ($rootScope) {
var socket = io.connect();
return {
on: function (eventName, callback) {
socket.on(eventName, function () {
var args = arguments;
$rootScope.$apply(function () {
callback.apply(socket, args);
});
});
},
emit: function (eventName, data, callback) {
socket.emit(eventName, data, function () {
var args = arguments;
$rootScope.$apply(function () {
if (callback) {
callback.apply(socket, args);
}
});
});
}
};
}]);
api.js (both find all object and single object)
apiRouter.get('/all_stories', function(req, res) {
Story.find({} , function(err, stories) {
if(err) {
res.send(err);
return;
}
res.json(stories);
});
});
apiRouter.get('/:story_id', function(req, res) {
Story.findById(req.params.story_id, function(err, story) {
if(err) {
res.send(err);
return;
}
res.json(story);
});
});
For api.js whenever I refresh the page for '/all_stories' or go to a '/:story_id' it will load the data for split seconds.
allStories.html
<div class="row">
<div class="col-md-3">
</div>
<!-- NewsFeed and creating a story -->
<div class="col-md-6">
<div class="row">
</div>
<div class="row">
<div class="panel panel-default widget" >
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span>
<h3 class="panel-title">
Recent Stories</h3>
<span class="label label-info">
78</span>
</div>
<div class="panel-body" ng-repeat="each in story.stories | reverse" >
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-xs-10 col-md-11">
<div>
<div class="mic-info">
{{ each.createdAt | date:'MMM d, yyyy' }}
</div>
</div>
<div class="comment-text">
<h4>{{ each.content }}</h4>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-3">
</div>
The loading problem you see is that the data is fetched after the view has been created. You can delay the loading of the view by using the resolve property of the route:
.when('/allStories', {
templateUrl : 'app/views/pages/allStories.html',
controller: 'AllStoryController',
controllerAs: 'story',
resolve: {
stories: function(Story) {
return Story.allStories();
}
}
})
Angular will delay the loading of the view until all resolve properties have been resolved. You then inject the property into the controller:
.controller('AllStoryController', function(socketio, stories) {
var vm = this;
vm.stories = stories.data;
});
I think you should use local storage. suited module - angular-local-storage
The data is kept aslong you or the client user clean the data,
Usage is easily:
bower install angular-local-storage --save
var storyService = angular.module('storyService', ['LocalStorageModule']);
In a controller:
storyService.controller('myCtrl', ['$scope', 'localStorageService',
function($scope, localStorageService) {
localStorageService.set(key, val); //return boolean
localStorageService.get(key); // returl val
}]);
Match this usage to your scenario (for example - put the stories array on and just append updates to it)

Getting undefined in AngularJS

I'm working on building a little app that accepts input from a form (the input being a name) and then goes on to POST the name to a mock webservice using $httpBackend. After the POST I then do a GET also from a mock webservice using $httpBackend that then gets the name/variable that was set with the POST. After getting it from the service a simple greeting is constructed and displayed back at the client.
However, currently when the data gets displayed now back to the client it reads "Hello undefined!" When it should be reading "Hello [whatever name you inputed] !". I used Yeoman to do my app scaffolding so I hope everyone will be able to understand my file and directory structure.
My app.js:
'use strict';
angular
.module('sayHiApp', [
'ngCookies',
'ngMockE2E',
'ngResource',
'ngSanitize',
'ngRoute'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.run(function($httpBackend) {
var name = 'Default Name';
$httpBackend.whenPOST('/name').respond(function(method, url, data) {
//name = angular.fromJson(data);
name = data;
return [200, name, {}];
});
$httpBackend.whenGET('/name').respond(name);
// Tell httpBackend to ignore GET requests to our templates
$httpBackend.whenGET(/\.html$/).passThrough();
});
My main.js:
'use strict';
angular.module('sayHiApp')
.controller('MainCtrl', function ($scope, $http) {
// Accepts form input
$scope.submit = function() {
// POSTS data to webservice
setName($scope.input);
// GET data from webservice
var name = getName();
// Construct greeting
$scope.greeting = 'Hello ' + name + ' !';
};
function setName (dataToPost) {
$http.post('/name', dataToPost).
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
// GET name from webservice
function getName () {
$http.get('/name').
success(function(data) {
$scope.error = false;
return data;
}).
error(function(data) {
$scope.error = true;
return data;
});
}
});
My main.html:
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<img src="../images/SayHi.png" class="logo" />
</div>
</div>
<div class="row text-center">
<div class="col-xs-10 col-xs-offset-1 col-md-4 col-md-offset-4">
<form role="form" name="greeting-form" ng-Submit="submit()">
<input type="text" class="form-control input-field" name="name-field" placeholder="Your Name" ng-model="input">
<button type="submit" class="btn btn-default button">Greet Me!</button>
</form>
</div>
</div>
<div class="row text-center">
<div class="col-xs-12 col-md-6 col-md-offset-3">
<p class="greeting">{{greeting}}</p>
</div>
</div>
At the moment your getName() method returns nothing. Also you cant just call getName() and expect the result to be available immediately after the function call since $http.get() runs asynchronously.
You should try something like this:
function getName () {
//return the Promise
return $http.get('/name').success(function(data) {
$scope.error = false;
return data;
}).error(function(data) {
$scope.error = true;
return data;
});
}
$scope.submit = function() {
setName($scope.input);
//wait for the Promise to be resolved and then update the view
getName().then(function(name) {
$scope.greeting = 'Hello ' + name + ' !';
});
};
By the way you should put getName(), setName() into a service.
You can't return a regular variable from an async call because by the time this success block is excuted the function already finished it's iteration.
You need to return a promise object (as a guide line, and preffered do it from a service).
I won't fix your code but I'll share the necessary tool with you - Promises.
Following angular's doc for $q and $http you can build yourself a template for async calls handling.
The template should be something like that:
angular.module('mymodule').factory('MyAsyncService', function($q, http) {
var service = {
getNames: function() {
var params ={};
var deferObject = $q.defer();
params.nameId = 1;
$http.get('/names', params).success(function(data) {
deferObject.resolve(data)
}).error(function(error) {
deferObject.reject(error)
});
return $q.promise;
}
}
});
angular.module('mymodule').controller('MyGettingNameCtrl', ['$scope', 'MyAsyncService', function ($scope, MyAsyncService) {
$scope.getName = function() {
MyAsyncService.getName().then(function(data) {
//do something with name
}, function(error) {
//Error
})
}
}]);

JSON request with Angular Displays an Empty Response

I believe Angular is loading the page before it receives all the information from JSONP. If I refresh the page a couple of times I do get the information to display; however, it is not constant. My code is almost the same as the code I am using on my projects page which does not have the same issue.
HTML:
<div class="container">
<div class="row push-top" ng-show="user">
<div class="col-xs-10 col-xs-offset-1 col-sm-10 col-sm-offset-1 col-md-10 col-md-offset-1">
<div class="well well-sm">
<div class="row">
<div class="col-sm-3 col-md-2">
<img ng-src="[[ user.images.138 ]]" alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-7 col-md-8">
<h4 ng-bind="user.display_name"></h4>
<h5 ng-bind="user.occupation"></h5>
<i class="fa fa-map-marker"></i>
<cite title="[[ user.city ]], [[ user.country ]]">[[ user.city ]], [[ user.country ]]</cite>
<br>
<strong ng-bind="user.stats.followers"></strong> Followers, <strong ng-bind="user.stats.following"></strong> Following
<hr>
<p style="margin-top:10px;" ng-bind="user.sections['About Me']"></p>
</div>
</div>
</div>
</div>
</div>
</div>
JavaScipt:
'use strict';
angular.module('angularApp')
.controller('AboutCtrl', function ($scope, $window, Behance) {
$scope.loading = true;
Behance.getUser('zachjanice').then(function (user) {
$scope.user = user;
$scope.loading = false;
}, function (error) {
console.log(error);
$scope.loading = false;
$scope.user = null;
});
$scope.gotoUrl = function (url) {
$window.location.href = url;
};
});
You can see the page in question at: http://zachjanice.com/index.html#/about. Thanks in Advance.
As requested here is the behance service:
'use strict';
angular.module('angularApp')
.factory('Behance', function ($http, $q, localStorageService, BEHANCE_CLIENT_ID) {
// Should be called to refresh data (for testing purposes)
// localStorageService.clearAll();
// Public API
return {
// Get a list of projects
getProjects: function (config) {
var pageNum = 1;
if (angular.isObject(config) && angular.isDefined(config.page)) {
pageNum = config.page;
}
var _projects = $q.defer(),
_storedProjects = localStorageService.get('Projects_Page_');
if (_storedProjects !== null) {
_projects.resolve(_storedProjects);
} else {
$http.jsonp('https://www.behance.net/v2/users/zachjanice/projects', {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK',
'page': pageNum
}
})
.then(function (response) {
if (response.data.http_code === 200 && response.data.projects.length > 0) {
// console.log('getting page', _page);
_projects.resolve(response.data.projects);
localStorageService.add('Projects_Page_' + pageNum, response.data.projects);
}
});
}
return _projects.promise;
},
// Get project with id
getProject: function (id) {
var _project = $q.defer();
$http.jsonp('https://www.behance.net/v2/projects/' + id, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_project.resolve(data.project);
});
return _project.promise;
},
// Get project with id
getUser: function (username) {
var _user = $q.defer();
$http.jsonp('https://www.behance.net/v2/users/' + username, {
params: {
'client_id': BEHANCE_CLIENT_ID,
'callback': 'JSON_CALLBACK'
},
cache: true
}).success(function (data){
_user.resolve(data.user);
});
return _user.promise;
}
};
});
Anthony Chu supplied no support, so I found the answer myself. The issue was not the Behance Service, but the Projects Controller like I had originally stated.
I changed $scope.loading under the call for the service from false to true. Works every time.

Categories

Resources