Auto refresh data from json to angular - angularjs

Good day, I want to create auto refresh, so when the data(s) updated the field will change too. So, i'm trying to use $interval. Please check my script
<script>
var app = angular.module('myApp', []);
app.controller('listsupport', function($scope,$http,$interval) {
var count = 0;
$http.get("<?=base_url();?>newchat/listsupport").then(function (response) {
$scope.names = response.data;
$interval( function(){listsupport();}, 10000);
});
});
</script>
with my script above, i get an error listsupport is not defined. How can i fix it ? thank's in advance.

Try this
var app = angular.module('myApp', []);
app.controller('listsupport', function($scope, $http, $interval) {
this.interval = $interval(function() {
$http.get("<?=base_url();?>newchat/listsupport").then(function(response) {
$scope.names = response.data;
});
}, 10000);
});

Related

How to all data at once and apply to controllers in angularjs

i want to get all data at once through AJAX($http) request and apply to all controllers
i picked this code from google it shows the i have to make requests for each controller were i can get data in once ajax call and apply objects according to the controlers i have tried factory in angular but it did't work please help me to find out a way where i can get data at once and update all data in controllers
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
thank you.
As per your comment, this will work:
mainApp.controller('ABC',function($rootScope){
$scope.somethingHappened = function(){
$rootScope.$emit('valueChanged',your_data_to_be_passed)
}
})
mainApp.controller('DEF',function($rootScope){
$rootScope.$on('valueChanged',function(event,data){
console.log(data) // you'll see your_data_to_be_passed
})
})
Since, the controllers are not related, you should prefer $rootScope events rather than $scope.$broadcast or $scope.$emit. You can get more details about them on online tutorials
You may use $rootScope instead
<p>Today's welcome message is:</p>
<h1>{{myWelcome}}</h1>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope){
$http.get("welcome.htm")
.then(function(response) {
$rootScope.myWelcome = response.data;
});
})
app.controller('myCtrl', function($scope, $http) {
// Here watch for scope
$scope.$watch("myWelcome", function(value){
console.log(value)
})
});
</script>
You could use localStorage and use JSON(stringify and parse) methods if the data is not a string, if its object access to properties, if its array access to index.
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope){
$http.get("welcome.htm")
.then(function(response) {
localStorage.setItem('data', JSON.stringify(response));
});
})
app.controller('anotherCtrl', function($scope, $http) {
$scope.myWelcome = JSON.parse(getItem('data'));
/*or you can do this
var full_data = JSON.parse(getItem('data'));
(object)$scope.myWelcome = full_data.[some_property];
(array of objects)$scope.myWelcome = full_data[index].[some_property];
(just array) $scope.myWelcome = full_data[index]
*/
});
</script>

Automatically update id variable in two controllers using $broadcast in AngularJS

$ctrl.clicker = function(id)
{
$rootScope.$broadcast('idBull', id);
}
When I mouseenter an image the above function gets called. I want to share the id in another controller and broadcast whatever changes where made to this id.
$scope.$on('idBull', function (event, data) {
console.log(data); // 'Data to send'
});
In the other controller I used the code to do a console loge of my id but got no results.
http://jsfiddle.net/87rLob9x/
Check this fiddle hope it helps
html
<html ng-app="myApp">
<div ng-controller='ControllerA'>
<button ng-click='add()'>Add</button
</div>
<div ng-controller='ControllerB'>
{{ increment }}
</div>
</html>
js:
var app = angular.module('myApp', [])
.controller('ControllerA', function($scope) {
$scope.increment = 0;
$scope.add = function() {
$scope.$broadcast('hasIncremented');
}
}).
controller('ControllerB', function($scope) {
$scope.$on('hasIncremented', function(event) {
$scope.increment++;
});
})
Not sure why you are not getting your code to work, maybe the controller with $scope.$on is not created/loaded when the $rootScope.$broadcast is executed?
Another solution is to use a service that you inject into both controllers and use that for communication instead. Example of broadcast solution:
var app = angular.module("app", [])
.controller("ControllerA", function($scope, $rootScope)
{
$scope.clicker = function(id)
{
$rootScope.$broadcast("id changed", id);
}
})
.controller("ControllerB", function($scope)
{
$scope.$on("id changed", function(event, id)
{
// Do whatever you need to do with id
});
});
Example of solution with custom service:
var app = angular.module("app", [])
.factory("customService", function()
{
var callbacks = [];
return {
onIdChange: function(callback)
{
callbacks.push(callback);
},
idChanged: function(id)
{
callbacks.forEach(function(callback)
{
callback(id);
});
}
};
})
.controller("ControllerA", function($scope, customService)
{
$scope.clicker = function(id)
{
customService.idChanged(id);
}
})
.controller("ControllerB", function(customService)
{
customService.onIdChange(function(id)
{
// Do whatever you need to do with id
});
});

Angular not displaying JSON array data

I've spent a few hours on this and I just can't get the array data to display on the page. I'm not getting any errors.
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', function($http){
this.files = [];
$http.get('angular-data.json').success(function(data){
this.files = data;
});
}]);
})();
And inside my angular-data.json file:
[{"name": "myfile.doc","ext": "doc","size": "168KB","modified": "5 mins"}]
Someone please help :-(
Convert your .success to .then
Then convert this
this.files = data;
to this
this.files = data.data;
Try this
this.files = data[0];
In angular-data.json file it have object in array
I think the this in success callback is not getting its context.
Try binding it in $scope or if you are using vm, just like
for $scope
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', '$scope', function($http, $scope){
$scope.files = [];
$http.get('angular-data.json').success(function(data){
$scope.files = data;
});
}]);
})();
For vm
(function() {
var app = angular.module('myApp', []);
app.controller('AppController', ['$http', function($http){
var vm = this;
vm.files = [];
$http.get('angular-data.json').success(function(data){
vm.files = data;
});
}]);
})();

Passing value from JSON http.get to scope.value using AngularJS

I am currently writing a code that is displaying the file from json to a charting JS.
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
viewAll.gauge = data;
});
$scope.value = viewAll.gauge[0].value;
However, I am having a hard time taking out the value from my variable array viewAll.gauge. I'm having an error in:
Error: viewAll.gauge[0] is undefined
#http://localhost:8080/js/directives/cpusagegauge.js:11:2
e#http://localhost:8080/js/angular.min.js:35:343
h/<.instantiate#http://localhost:8080/js/angular.min.js:35:474
ce/this.$get</<#http://localhost:8080/js/angular.min.js:68:140
x/<#http://localhost:8080/js/angular.min.js:54:226
q#http://localhost:8080/js/angular.min.js:7:384
x#http://localhost:8080/js/angular.min.js:54:89
g#http://localhost:8080/js/angular.min.js:48:28
g#http://localhost:8080/js/angular.min.js:48:1
g#http://localhost:8080/js/angular.min.js:48:1
x#http://localhost:8080/js/angular.min.js:55:10
g#http://localhost:8080/js/angular.min.js:48:28
x#http://localhost:8080/js/angular.min.js:55:10
z/<#http://localhost:8080/js/angular.min.js:61:261
l/k.success/<#http://localhost:8080/js/angular.min.js:73:32
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/e/m.promise.then/L#http://localhost:8080/js/angular.min.js:99:147
Re/f/<.then/<#http://localhost:8080/js/angular.min.js:100:321
me/this.$get</g.prototype.$eval#http://localhost:8080/js/angular.min.js:111:1
me/this.$get</g.prototype.$digest#http://localhost:8080/js/angular.min.js:108:458
me/this.$get</g.prototype.$apply#http://localhost:8080/js/angular.min.js:112:323
g#http://localhost:8080/js/angular.min.js:73:285
x#http://localhost:8080/js/angular.min.js:77:322
Ne/</y.onreadystatechange#http://localhost:8080/js/angular.min.js:78:358
http://localhost:8080/js/angular.min.js
Line 93
BTW, my JSON file is pretty small.
[{
"value": "80"
}]
The problem is that the callback of $http.get() is called asynchronously. In your case viewAll.gauge = data;is called after $scope.value = viewAll.gauge[0].value;
The following should work:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.value = data.gauge[0].value;
});
})
Additionally if you want to update scope variables in async callbacks you have to wrap it in $scope.$apply(function() { //your code goes here });. Here is the full example:
var app = angular.module('cpu-usage', []);
app.controller('GaugeController', ['$scope', '$http',
function($scope, $http) {
var viewAll = this;
viewAll.gauge = [];
$http.get('dom/json/cpuUsage.json').success(function(data){
$scope.apply(function() {
$scope.value = data.gauge[0].value;
});
});
})

can controllers create arbitrary properties in the $rootScope in Angular

Is it legal for a controller to do something like this in Angular?
$rootScope.someArbitaryObject = ["fee", "fie", "fo", "fum];
or
$rootScope.foo = {name: "Jane Q. Public", favoriteColor: "green"}
Yes, it is legal but only if you want ALL controllers to have access to that model.
A better practice is to use services that you can then inject to one or more controllers:
var myApp = angular.module('myApp', []);
myApp.factory('MyService', function () {
return { message: "I'm data from a service" };
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService;
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService;
});
Any change you make to MyService properties in one controller will affect all the other controllers that use MyService.
regarding the question in your comments, a good way to share date is through localstorage (or sessionStorage). I wrote a storageService which allows you to save, load and delete.
angular.module(yourApplication).service('storageService', [
function() {
// implementation using localStorage. Future possibility to user $cookie service here, or sessionStorage, depends on what you want
return {
save: function(key, jsonData, expirationMin){ // default is 30 minute expiration
if(!expirationMin)
expirationMin = 30;
var expirationMS = expirationMin * 60 * 1000;
var record = {
value: JSON.stringify(jsonData),
timestamp: new Date().getTime() + expirationMS
};
localStorage.setItem(key, JSON.stringify(record));
return jsonData;
},
load: function(key){
var record = JSON.parse(localStorage.getItem(key));
if (!record){
return false;
}
return (new Date().getTime() < record.timestamp && JSON.parse(record.value));
},
remove: function(key){
localStorage.removeItem(key);
}
};
}
]);
Another way using services (Modified Yoni's code a little):
var myApp = angular.module('myApp', []);
myApp.service('MyService', function () {
var someData = 'test';
return {
getData: function(){ return someData},
setData: function(input){ someData = input;}
};
});
myApp.controller('FirstCtrl', function($scope, MyService) {
$scope.data = MyService.getData();
});
myApp.controller('SecondCtrl', function($scope, MyService) {
$scope.data = MyService.getData;
});

Resources