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>
Related
I have a server set up on localhost:5000 that has a JSON string that contains "Hello world"
I want my AngularJS application to fetch this data, and display it.
here is what I have.
this is the script getJSON.js
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "localhost:5000"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
this is how I call it in my html
<div ng-app="myApp" ng-controller="myCtrl">
<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("localhost:5000")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
now the "myWelcome" should be "Hello world" but it just displays myWelcome when I run the code.
the backend is fully working! I've done it with regular Angular but need it to work with AngularJS unfortunately.
Any advice?
This is not a full answer I see what you're trying to do. It looks like you're not calling the correct controller and your value never gets updated. Move your app definition into your script tags and remove the controller that you have there
//index.html
<script>
var app = angular.module('myApp', []);
</script>
// myCtrl.js
app.controller('myCtrl', function($scope, $http) {
$scope.myWelcome = 'test';
$http({
method : "GET",
url : "localhost:5000"
}).then(response) {
$scope.myWelcome = response.data;
}, catch(error) {
$scope.myWelcome = error;
});
});
Next check your network tab and see if the request is actually executed. If it is not then you're controller is not connected to the app properly. You should be able to set breakpoints at this time and see what is firing and what is not.
EDIT: Also make sure you're loading your js file into your view after the first script tag is fired. Otherwise 'app' will not be defined.
So I am trying to share data between two controllers on an on-click event. My code is as follows:
Controller
function userTypeController($scope, $location, CategoryService) {
let vm=this;
vm.getCat=function(){
CategoryService.getCategories() .then(function (response)
{
$scope.categories=response.data.data.categories;
$scope.index = 0;
$scope.array = [];
for(var i=0; i<$scope.categories.length/2;i++)
$scope.array.push(i);
});
$location.path('/category');
};
};
Say in my html for that controller, I have a button that calls the getCat function.
<md-button md-whiteframe="8" ng-click="utCtrl.getCat()">Submit<md-button>
In my category service , I have a function that returns a list of categories.
Service
return {
getCategories: function () {
return $http.get(url2);
}
Now i want the array of categories that I get from the server to be accessible in my Categories controller. I was using $rootScope before to share the date from usertype controller to the other one but its not the ideal thing to do. I want $scope.array to be accessible in my categories controller so i can display that in its view. What would be the best way to do this. Thanks a lot!
You should consider using a service in this case to share the data across your controllers.
SharedService.js
app.service('sharedService', function(){
var categories = [];
names.add = function(incategories){
categories = incategories;
};
names.get = function(){
return categories;
};
});
then inject in your controller1 and controller2 and use depending on your requirement.
app.controller("TestCtrl",
function($scope,sharedService) {
$scope.categories =[];
$scope.save= function(){
sharedService.add(yourcat);
}
}
);
and then use it as,
app.controller("TestCtrl2",
function($scope,sharedService) {
$scope.getcategories = function(){
$scope.categories = sharedService.get();
}
}
);
This will get you results instantly, No need of service or anything,You can use $broadcast for multiple controllers as well :
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="sendData();"></button>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($rootScope, $http) {
function sendData() {
var arrayData = [1,2,3];
$rootScope.$emit('eventName', arrayData);
}
});
app.controller('yourCtrl', function($rootScope, $http) {
$rootScope.$on('eventName', function(event, data) {
console.log(data);
});
});
</script>
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);
});
I'm new to web development and can't seem to find the answer to this question anywhere. I want my NodeJS API endpoint to be called with every ng-click, not just when the page gets loaded. Here is what I have so far:
HTML:
<button ng-click="myFunction()">Click me!</button>
Angular:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.post("/test").then(function(response) {
$scope.testString = response.data;
});
});
NodeJS
app.get('/test', function(req, res) {
console.log("test get");
});
Is this what you're looking for?
HTML:
<button ng-click="myFunction()">Click me!</button>
Angular:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myFunction = function() {
$http.post("/test").then(function(response) {
$scope.testString = response.data;
});
}
});
I have two controllers- searchBoxController and productList. What I am trying to do is to update the scope variable $scope.products from multiple controllers. I know that defining it as a root variable is a very bad design- but putting that in shared service is not solving the problem. The update doesn't reflect in the HTML templates!
function SearchTermService(){
this.productSearch = function(data, $http){
var url = "";
$http.get(url).then(function(resp){
return resp.data;
},
function(err){
console.log(err);
});
};
};
var app = angular.module('app', []);
app.service("myService", MyService);
app.service("searchTermService", SearchTermService);
app.run(function($rootScope) {
$rootScope.products = new Date();
});
app.controller('productList', function ($scope, $rootScope, $http, myService) {
$rootScope.products = prod_res;
});
app.controller('searchBoxController', function($scope, $http, searchTermService, $rootScope){
$scope.getSearchResults = function(){
$rootScope.products = searchTermService.productSearch($scope.term, $http)
};
});
PS: I am not sure if I need to have a promise returned while assigning the $rootScope.products in 'searchBoxController', as the console.log says its undefined. Currently I am not returning a promise from the service.
In order to update a scope variable across multiple controller, you can use angular service.
You should use this because all angular services are singletons, so you can easily share common logic, share data between controller.
I've made an example where I use service in order to update some data. Then, my factory return an object data, so we will get an object, not just a fixed value. Thanks to this, our data will be updated, we will keep the binding data.
Controller
(function(){
function Controller($scope, $timeout, Service) {
//Retrieve current data object of our service
$scope.data = Service.value;
//will be set to 4
$timeout(function(){
Service.set(4, 'product');
}, 1000);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller2($scope, $timeout, Service) {
//Retrieve current data object of our service
$scope.data2 = Service.value;
}
angular
.module('app')
.controller('ctrl2', Controller2);
})();
Service
(function(){
function Service() {
//Our data object
var data = {
product: null
};
function set(value, field){
data[field] = value;
}
return {
set: set,
value: data
};
}
angular
.module('app')
.factory('Service', Service);
})();
HTML
<body ng-app='app'>
<div ng-controller='ctrl'>
<h2>Service value : {{data.product}}</h2>
</div>
<div ng-controller='ctrl2'>
<h2>Service value from controller2 : {{data2.product}}</h2>
</div>
</body>
So, we will share our data across multiple controller. By using services, you can avoid to use the $rootScope.
You can see the Working plunker