I'm fairly new to angular js, and not really sure how to google the terms i need.
I basically have a html page, bind to a controller. This page will load data from mysql.
in my controller, i have code like this when the page load:
thresholdNameSpace.controller("ThresholdController", ['$scope','$http', function ($scope, $http){
$http.get('http://something.appspot.com/met').success(function(data){
$scope.messages = data;
}]);
There is a functionality on the page that add new entry to the database. How do i update the controller so that after a new content is added to the database, it automatically gets displayed?
what keyword should i be looking for in angularjs term
well, just push the data to the server and send a response back... a brute-force approach would be to send back the entire data back, or just to append the current 'message' at the end of the messages object
thresholdNameSpace.controller("ThresholdController", ['$scope','$http', function ($scope, $http){
// get data
$http.get('http://something.appspot.com/met').success(function(data){
// assuming messages is an array
$scope.messages = data;
});
// create a function to push data up to the db, then update the view on success or failure appropriately
$scope.updateDatabase = function(param1, param2, param3...){
var parameters = {
name: param1,
date: param2,
message: param3
}
$http.get('http://something.appspot.com/metUpdate', parameters).then(function(successResponse){
console.log('successResponse', successResponse);
if($scope.messages)
$scope.messages.push({message: param3, person: param1, sent: param2}); // your object added to array
}, function(failureResponse){
console.log('failureResponse', failureResponse);
// you can also push a error object which will be processed on the front end for proper display
$scope.messages.push({error: failureReason.data.errorMessage});
});
}
}]);
Angular automatically updates the html, you just have to update $scope.messages from the database.
For example, you can get the data every 30 seconds, with $interval.
Something like this :
var update = function() {
$http.get('http://something.appspot.com/met').success(function(data){
$scope.messages = data;
}
}
$interval(update, 30000)
Don't forget to inject $interval in your controller.
Related
I have a service defined which do the db related queries/updates. I have defined the controller which does the data parsing for the angular elements by getting the objects from the service. I would like to keep each scope different
How can I pass the data from service to controller using ngResource.
Sample Service:
app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
var svc = {};
var home = $resource('/home/getAll');
var dbData= home.get();
svc.getRooms = function() {
return dbData;
};
return svc;
}]);
Sample Controller:
app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
$scope.dbData = ioHome.getRooms();
//Here UI specific objects/data is derived from dbData
}]);
After the DB is queried and the results are avialble the dbData in service is reflecting the data from DB, but the Controller cannot get that data
It is important to realize that invoking a $resource object method
immediately returns an empty reference (object or array depending on
isArray). Once the data is returned from the server the existing
reference is populated with the actual data. This is a useful trick
since usually the resource is assigned to a model which is then
rendered by the view. Having an empty object results in no rendering,
once the data arrives from the server then the object is populated
with the data and the view automatically re-renders itself showing the
new data. This means that in most cases one never has to write a
callback function for the action methods.
From https://docs.angularjs.org/api/ngResource/service/$resource
Since the 'ioHome.getRooms();' is being called before the $resource has returned the data you are getting dbData as an empty reference
app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
var svc = {
dbData : {}
};
var home = $resource('/home/getAll');
var svc.dbData.rooms = home.get();
return svc;
}]);
Controller
app.controller("homeCtrl",["$scope","$mdDialog","ioHomeService",function($scope,$mdDialog,ioHome){
$scope.dbData = ioHome.dbData;
//You can access the rooms data using $scope.dbData.roooms
//Here UI specific objects/data is derived from dbData
}]);
You would have to return the service object , like so :
app.factory("ioHomeService", ["$rootScope","$resource", function($rootScope,$resource) {
var svc = {};
var home = $resource('/home/getAll');
var dbData= home.get();
svc.getRooms = function() {
return dbData;
};
return svc; //here
}]);
Currently the getRooms method is not visible to your controller.
I am working on displaying collection that I got from DB in angular with firebase DB. I have those controller and service setup. in the html, I use search.users expecting it will hold all the data that I got from the DB but it won't show up. I can't figure out why. I tried few things like angular.copy or $broadcast with no luck. Can anyone help advise on this? Appreciated in advance.
.controller('SearchController', function ($scope, SearchService, logout, $location){
var search = this;
search.users = SearchService.users;
//$scope.$on('evtputUsers', function () {
// search.users = SearchService.users;
//});
})
//service for SearchService
.factory('SearchService', function ($http, $rootScope){
var userRef = new Firebase("app url");
var broadcastUsers = function () {
$rootScope.$broadcast('evtputUsers');
};
//get the user info
//insert the data to the db.
//retrieving the data
var dbUsers;
userRef.child('users').on('value', function(snapshot){
dbUsers = snapshot.val();
// angular.copy(snapshot.val(), dbUsers);
console.log('usersinDB:',dbUsers);
broadcastUsers();
}, function(err){
console.error('an error occured>>>', err);
});
return {
users: dbUsers
};
})
Rather than using $broadcast() and $on() you should use the AngularFire module.
AngularFire provides you with a set of bindings to synchronizing data in Angular.
angular.module('app', ['firebase']) // 1
.controller('SearchCtrl', SearchCtrl);
function SearchCtrl($scope, $firebaseArray) {
var userRef = new Firebase("app url")
$scope.users = $firebaseArray(userRef); // 2
console.log($scope.users.length); // 3
}
There are three important things to take note of:
You need to include AngularFire as firebase in the dependency array.
The $firebaseArray() function will automagically synchronize your user ref data into an array. When the array is updated remotely it will trigger the $digest() loop for you and keep the page refreshed.
This array is asynchronous. It won't log anything until data has populated it. So if you're logs don't show anything initially, this is because the data is still downloading over the network.
Could you please tell me how to send data from one view to another using state. I don't want to use factory or service. I need to send the data using url and get the data from url and display it on view.
I have one field name in my first View. I want to display on the second view whatever user enters in the input field. On button click, I need to send it to another view. I am able to go to the next view but how to send the data?
Plunker
http://plnkr.co/edit/iDlzhzkz0pJKN2f2CZZe?p=preview
var loginCntrl = function($scope, $location, $state) {
$scope.testClick = function() {
$state.go("navigation2");
}
$scope.name = "";
/*$scope.fullname = function() {
return $scope.firstname + $scope.lastname;
};*/
}
$state.go can have a parameters object to pass on to the view
Check here: https://github.com/angular-ui/ui-router/wiki/Quick-Reference#stategoto--toparams--options
$state.go("State", {Hello:"Hi!"});
You can then pick up those params on the view controller using $stateParams
app.controller("SomeController", function($scope, $stateParams){
$scope.NewHello = $stateParams.Hello;
})
You will also need to amend the URL to accept this parameter:
url:"/someurl/{Hello}
I have a service with the following:
.service('TasksService', function ($http) {
return $http.jsonp('http://blabla/json/?callback=JSON_CALLBACK');
});
My controller:
.controller("TasksCtrl", function ($scope, TasksService) {
TasksService.then(function (TasksService) {
$scope.Tasks = TasksService;
});
});
This shows list with many items.
But I have another service and another controller. I change an item there and when I save and post data to database and I get back to initial list, I still see the old listed items. I must refresh the browser to see what I have edited.
In the second controller I have save function with this:
$scope.saveTask = function () {
$http.post('http://blabla', $scope.Task.data).then(function (data) {
// This shows the very first state with all the listed items
$state.go('tasks');
});
};
When I save the changes and state.go() shows me the first screen I do not know why the data is not with the new changes from the service returned data. It seems like the screen is just changed but the new data is not returned from the service. Any ideas how to fix this?
I got it working. I changed my service and controller. In my service I returned an object with another method and then I changed my controller also to use the returned method.
The service:
.service('TasksService', function ($http) {
return {
getTasks: function() {
return $http.jsonp('http://blabla/json/?callback=JSON_CALLBACK');
}
};
});
And the controller:
.controller("TasksCtrl", function ($scope, TasksService) {
TasksService.getTasks().then(function (data) {
$scope.Tasks = data;
});
});
Now it is working and I see the items list the new saved and returned data. Thank you!
All you need is to reflect the changed data into your html
Angular has a method for this
$scope.$apply();
This method works both with parameters as well as without parameters.
Hope this helps.
Basically i have two sources of data, one is real time data from socket.io and other is json object. And i'm using both in front-end but the problem is that i need to pass a variable from socket.io to json parser:
This controller for my view:
.controller('mainCtrl', ['$scope','socket','currentData', function($scope, socket, currentData){
// It's updated every 2 seconds
socket.on('chnl', function(data){
// Passed to view OK
$scope.realtimeData = data;
// And i need to pass this to currentData.
$scope.foo = data.foo;
});
// Here i'm getting json response from factory which is computed based on socket.io foo variable and then passed to view.
currentData.get().then(function(data){
if($scope.foo)...
...
$scope..
});
}]
The problem is anything i tried i ended up calling json object on every incoming socket.io package, what i need to calc this at it's initalization and pass data to the view.
Any solutions?
Thanks.
If you need for it to run only once for initialization...
Move the call to the JSON service into the .on callback. Place it inside of a conditional which runs only when an initialization variable is set to false. Once the data is set, switch that variable to true so that it doesn't run again:
.controller('mainCtrl', ['$scope','socket','currentData', function($scope, socket, currentData){
$scope.fooInit = false;
socket.on('chnl', function(data){
$scope.realtimeData = data;
$scope.foo = data.foo;
if (!$scope.fooInit) {
currentData.get().then(function(data){
if($scope.foo)...
...
$scope..
});
$scope.fooInit = true;
}
});
}])