This is the code of one controller from my application, in the User page.
app.controller('UserCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/Users/GetUsers').success(function (data) {
$scope.data = data;
});
this.search = function () {
$http.post('/Users/SearchUser', $scope.search).success(function (data) {
$scope.data = data;
});
}
this.delete = function() {....}
}]);
On another page, the Permission page, I create a controller with the same logic
app.controller('PerCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('/Permission/GetPermissions').success(function (data) {
$scope.data= data;
});
this.search = function () {
$http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
$scope.data = data;
});
}
this.delete = function() {....}
}]);
As you can see, the only different is the URL. How can I reuse the logic from a controller to another?
That is exactly what services are for.
So instead of:
$http.get('/Permission/GetPermissions').success(function (data) {
$scope.data= data;
});
You'd call something like:
permissionsService.get().then(function (data) {
$scope.data= data;
});
And:
this.search = function () {
$http.post('/Permission/SearchPermission', $scope.search).success(function (data) {
$scope.data = data;
});
}
Replaced with something like:
this.search = function () {
searchService.search().then(function (data) {
$scope.data = data;
});
}
etc...
Generally, all server calls should be in services anyway, so there's a great opportunity to improve your code and learn how to do it right.
Related
js1.js
app.controller('test1Controller',
function($scope,$http,$ngBootbox,$location,CRUDService,NotificationService,constants,ngWizard) {
$scope.fun1 = function(){
$http.get(context+"/back/demande/rest/test1").success(function(data, status) {
$scope.dto = data;
});
};
});
js2.js
app.controller('test2Controller',
function($scope,$http,$ngBootbox,$location,CRUDService,NotificationService,constants,ngWizard) {
$scope.fun2 = function(){
$http.get(context+"/back/demande/rest/test2").success(function(data, status) {
$scope.dto = data;
});
};
});
How can I call fun1 => js1.js in js2.js?
First, you need to move your function to angular.js service instance.
Then you need to inject this service to your controllers, like NotificationService.
Then you can call in different controllers.
app.service('myHttpService', ['$http', function($http) {
this.getData = function(context, endpoint) {
return $http.get(context+"/back/demande/rest/" + endpoint);
};
}]
// do not forget to use injector if you don't have ngAnnotate
app.controller('test2Controller', function($scope, $http, $ngBootbox, $location, CRUDService, NotificationService, constants, ngWizard, myHttpService) {
$scope.dto = null;
$scope.fun2 = function(){
myHttpService.getData(context, 'test1')
.then(function(data, status) {
$scope.dto = data;
});
};
});
I did pretty simple plunker to show my problem. The problem is I have variable and I want to populate this variable with initial app loading, I did angular services for this purpose, but for some reason angular services doesn't fire inside controller. Where is my mistake?
app.controller('MainCtrl', function($scope, optService) {
$scope.priority = [];
var exeService = function() {
console.log('function fired')
// this is firing
optService.myOptions(function (result) {
console.log('service fired')
// this is not firing
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});
}
exeService()
console.log($scope.priority)
// shows an empty array
});
services
(function () {
angular.module("app").factory("optService", ["$http", "$rootScope", "$q", "$log",
function ($http, $rootScope, $q, $log) {
var clearApi = "test.json";
function myOptions () {
return $http.get(clearApi)
.then(function (response) {
console.log(response.data)
// shows an array
return response.data;
});
}
return {
myOptions: myOptions
}
}])
}());
You should do the service declaration like that:
app.controller('MainCtrl', ['$scope', 'optService', function($scope, optService) {
and in the controller
optService.myOptions().then(function (result) {
console.log('service fired')
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});
i have used Angularjs and i wanna call getcustomer function from one controller to another controller i have so many doing gooogling but i don't have an idea that how to call that
i have write below code which i used
var app = angular.module('Napp', []);
app.controller('GetAlphabetical', function ($scope, $http) {
function getCutomers() {
$scope.loading = true;
$http.get('#Url.Content("~/Home/GetPesrons")').then(function (response) {
//var _data = angular.fromJson(response);
$scope.loading = false;
$scope.Customer = response.data; // please check the request response if list id in data object
}, function (error) {
throw error;
})
}
});
and second controller :
app.controller('MainCtrl', function ($scope, $http) {
getCutomers()
});
Mate, you will have to follow the following steps to resolve your problem. Firstly you have you create a factory
angular
.module('Napp')
.factory('CustomerFactory', ['$http', function ($http) {
var _factory = {};
_factory.getCustomers = function () {
return $http.get('#Url.Content("~/Home/GetPesrons")');
};
return _factory;
}]);
Then you can share data and functions between multiple controllers or services
GetAlphabetical Controller :
angular
.module('Napp')
.controller('GetAlphabetical', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
MainCtrl Controller :
angular
.module('Napp')
.controller('MainCtrl', ['$scope', 'CustomerFactory', function ($scope, CustomerFactory) {
loadCustomers();
function loadCustomers() {
CustomerFactory.getCustomers().then(function (successResponse) {
$scope.Customer = successResponse.data; // please check the request response if list id in data object
}, function (errorResponse) {
throw error;
})
}
}]);
This can be easily done by defining it as a service and injecting it as a dependency.
var app = angular.module('myApp', []);
myApp.service('helloWorldFromService', function() {
this.sayHello = function() {
return "Hello, World!"
};
});
app.controller('MainCtrl', function ($scope, $http, helloWorldFromService) {
app.controller('GetAlphabetical', function ($scope, $http, helloWorldFromService) {
Angular Service
What you want to do is to somehow communicate between two controllers. This can be easily be achieved using $broadcast & $on.
Incase there is a parent child relation between your controllers, use the following.
function firstCtrl($scope){
$scope.$broadcast('someEvent', [1,2,3]);
}
function secondCtrl($scope){
$scope.$on('someEvent', function(event, mass) {console.log(mass)});
}
If there is no parent child relationship between your controller, then inject $rootScope and broadcast using that.
related question - https://stackoverflow.com/a/14502755/1182982
I want to call a method from one controller to another controller. There are two controllers named "header" and "mainContent". Need to call a "trigger method" in the "header Controller", After the success call of "result method" in the mainController.
If that method called that should hide that paragraph.
<div ng-controller="header">
<p ng-show="msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($scope, $location) {
$scope.msg=true;
$scope.trigger= function(data) { //This method should be called after the result method called in the mainContent Controller
$scope.$on('UPDATE_CHILD', function() {
if(data)
$scope.msg=false;
});
}
});
// mainContent controller
module.controller('mainContent', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$scope.$broadcast('UPDATE_CHILD');
//From here I want to call trigger method of header controller
}
})
};
});
did u try this?
module.controller('header', ['$scope', '$location', '$rootScope', function ($scope, $location, $rootScope) {
$scope.msg=true;
$scope.trigger= function(data) {
if(data)
$scope.msg=false;
};
$rootScope.$on('event:fire', $scope.trigger);
}]);
// mainContent controller
module.controller('mainContent', ['$scope', '$location', 'dataService', function ($scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.$broadcast('event:fire');
}
})
};
}]);
You can use $rootScope like:
<div ng-controller="header">
<p ng-show="$root.header.msg">Content</p>
</div>
<div ng-controller="mainContent">
</div>
var module = angular.module("sourceViewer", ['ui.router']);
//header controller
module.controller('header', function ($rootScope,$scope, $location) {
$rootScope.header.msg = true;
});
// mainContent controller
module.controller('mainContent', function ($rootScope,$scope, $location, dataService) {
$scope.user = dataService.user;
$scope.signIn = function (user) {
var result = dataService.login(user);
result.success(function (data) {
if (data.message== "success") {
$rootScope.header.msg = true;
}
})
};
});
in the follwoing code you can see headerController is calling alert in mainController
myApp = angular.module("myApp",[]);
myApp.service("myService", function(){
showAlertBool = false;
return {
showAlert: function (value) {
showAlertBool = value;
},
canShowAlert: function () {
return showAlertBool;
}
}
});
myApp.controller("headerController", function($scope, myService){
console.log(myService);
$scope.clickHandler = function(){
myService.showAlert(true);
}
});
myApp.controller("mainController", function($scope, myService){
console.log(myService);
$scope.getServiceValue = function(){
return myService.canShowAlert();
}
$scope.$watch("getServiceValue()", function(newValue, oldValue){
if(newValue === true && newValue !== oldValue){
myService.showAlert(false);
alert("I can show Alert now!!!");
}
});
});
For a working code you can go here
I am currently working myself through tutorials and books teaching AngularJS.
I want to write a simple app, that loads some user data from a json file and displays it.
Now this is the relevant part of a JavaScript file, which does what I want:
Here is my Code :
angular.module('myModule', [])
.controller('myCtrl', function($scope, $http) {
$http.get('../mockdata/users_js.json').success(function(data, status, headers, config) {
$scope.users = data;
});
});
Now if I try to create a separate module for importing my data, I fail:
angular.module('myModule', [])
.controller('myCtrl', function($scope, Users) {
$scope.users = Users.query();
})
.factory('Users', function($http) {
var users = {};
users.query = function() {
// In real apps, we'd pull this data from the server...
$http.get('../mockdata/users_js.json').success(function(data, status, headers, config) {
this.data = data;
});
return this.data;
};
return users;
});
What am I doing wrong ?
And How can i fix this ?
In users.query() you kick off an asynchronous HTTP request, and then before it has a chance to finish return this.data which is undefined.
You could take a look at $resource, it returns a promise that you can assign to a $scope variable immediately. It will apply the right value when the request completes.
.factory('Users', function($resource) {
var users = {};
users.query = function() {
return $resource('../mockdata/users_js.json').get();
};
return users;
});
If you want to know how to do this with $http:
angular.module('myModule', [])
.controller('myCtrl', function($scope, Users) {
Users.then(function(data){
$scope.users = data;
});
})
.factory('Users', function($http) {
var Users = {};
Users = $http.get('../mockdata/users_js.json').then(function (response) {
return response.data;
});
return Users;
});
Here's a live Plnkr.