Let's say I have the following files:
JS1 file:
var app = angular.module('myApp', []);
app.controller('myCtrlOfJs1', function ($scope, $http) {
$http.post("url", data).success(function(data, status) {
$scope.hello = data;
})
})
JS2 file:
var app = angular.module('myApp', []);
app.controller('myCtrlOfJs2', function ($scope, $http) {
// $http.post("url", data).success(function(data, status) {
// $scope.hello = data;
// })
})
What I don't want is rewrite the same code twice. Then I want to call that function in my JS1 file, in the JS2 file. Is it possible?
PS: It's only an example, my code has much more lines than it.
Any help is appreciated. Thanks.
You can always use services: https://docs.angularjs.org/guide/services
app.factory('commonFeatures', function($http) {
return {
setHelloMsg: function(scope) {
$http.post("url", data).success(function(data, status) {
scope.hello = data;
})
}
};
});
app.controller('myCtrlOfJs1', function ($scope, commonFeatures) {
commonFeatures.setHelloMsg($scope);
});
edit:
As a response to your comment:
Well, it can be located nearly everywhere. Have a look at https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#single-responsibility. There are more style guides, but I personally follow this one and it just makes sense.
Your view doesn't have to change at all.
In general, you want to separate common functionality like this out into angular services: https://docs.angularjs.org/guide/services
In this example it might look like this:
var andyModule = angular.module('anyModule', []);
andyModule.factory('helloDataService', function($http) {
var helloDataService = {
// returns a promise
getHelloData = function() {
return $http.post("url", data)
}
};
return shinyNewServiceInstance;
});
And in your controller
app.controller('myCtrlOfJs1', function ($scope, $http, helloDataService) {
helloDataService.getHelloData().success((data)=> {
$scope.data = data;
})
})
I would abstract this to a service. Services are particularly good spots for things like network calls.
By the way using angular.module("app", modules) syntax will create an app named app, so JS2 file will overwite the module from JS1. I doubt you intend this.
angular.module("app", []);
var app = angular.module('myApp');
app.controller('myCtrlOfJs1', function ($scope, hello) {
hello.post().then(data => scope.$hello = data);
});
var app = angular.module('myApp');
app.controller('myCtrlOfJs2', function ($scope, hello) {
hello.post().then(data => scope.$hello = data);
});
app.factory("hello", function ($http) {
// set data somehow
return {
post() {
return $http.post("url", data);
},
};
});
This still duplicates the scope.$hello code which may be what you want to avoid. In this case you can extend from another controller that implements this either using newer class syntax or through the prototype. In this case I think it would be better to use controllerAs instead of $scope.
This is a method you can achieve what you are looking for.
I prefer the service method though
Take a look at this :
use case for $controller service in angularjs
https://docs.angularjs.org/api/ng/service/$controller
Hope it helps
Related
Login.js:
app.controller('LoginFormController', ['$scope','$http','$rootScope', '$state', function($scope, $http, $rootScope, $state) {
$scope.user = {};
$scope.authError = null;
$scope.login = function() {
$scope.authError = null;
var emailId = $scope.user.email;
var password = $scope.user.password;
$http({
url: 'http://localhost:8090/login/login',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'email='+emailId+'&password='+password
//data: {'email': $scope.user.email, 'password': $scope.user.password}
}).then(function(response) {
console.log(response.data);
if (response.data.status == 'SUCCESS') {
$scope.user = response.data.user.firstName;
$rootScope.test = response.data.user.firstName;
console.log("check: ",$rootScope.test)
$state.go('app.dashboard');
} else {
//alert('invalid login');
$scope.authError = 'Email or Password not right';
}
}, function(x) {
$scope.authError = 'Server Error';
})
};
}])
I saved the value under $rootScope.test
Here Is my App.main.js:
'use strict';
angular.module('app').controller('AppCtrl', ['$scope','$rootScope',
function($scope, $rootScope) {
$scope.user5 = $rootScope.test;
}
]);
trying to print the rootscope
If I run this Code i am facing the error of $rootScope is undefined in the console. How to Resolve this
$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.
Here is a modified version
https://jsfiddle.net/sedhal/g08uecv5/17/
angular.module('myApp', [])
.run(function($rootScope) {
$rootScope.obj = {
"name":"user1",
"bdate":"18/11/1994",
"city":"Ahmedabad"
};
})
.controller('myCtrl', function($scope, $rootScope) {
$scope.data = $rootScope.obj;
})
.controller('myCtrl2', function($scope, $rootScope) {
$scope.data1 = $rootScope.obj;
});
There is a useful answer to your question here: https://stackoverflow.com/a/18881189/9013688
Instead of passing directly your property on the $rootScope, you could emit an event which could be listened in an other part of your app like this:
if (response.data.status == 'SUCCESS') {
$rootScope.$emit('user-logged', response.data.user.firstName)
}
And then:
$rootScope.$on('user-logged', function(event, data){
do something with your data
})
Or you could use a service which is a good way to handle your data in all your app.
Please ensure that you take the advice of georgeawg, his suggestion seems to be the best way to implement this functionality in my opinion.
I want to suggest what might be wrong with your example.
If you can see that in the main App.main.js you have given the declaration as
angular.module('app').controller(...
But you are using a variable app in login.js like so.
app.controller(...
Which I am assuming you are creating somewhere else. Thus the set rootscope value is lost because there are two instances of the same app.
The solution to your problem will be to declare one variable app which will store the instance of the app. So the fix for your solution will be to modify App.main.js to be like so.
var app = angular.module('app');
app.controller(...
Also you need to remove any other arbitary var app = in your complete code, since these will create multiple instances of the same app.
I hope my explanation was understandable and the correct guess, please try out this solution!
In your main js add this.
app.run(['$rootScope', function($rootScope) {
$rootScope.test;
}]);
Here is a sample implementation of george's suggestion which is the proper way to handle this.
app.controller('LoginFormController', ['$scope','$http','$rootScope', '$state', 'stateService', function($scope, $http, $rootScope, $state, stateService) {
var userFirstName = 'John';
stateService.setFirstName('Bill');
userFirstName = stateService.getFirstName();
console.log(userFirstName); // result will be 'Bill'
}])
And the service which I usually call stateService
app.factory('stateService', [factory]);
function factory() {
var userFirstName = null;
stateService.getFirstName = function() {
return userFirstName;
};
stateService.setFirstName = function(firstName) {
userFirstName = firstName;
};
return stateService;
}
I have a resource file that sometimes is read, and sometimes is undefined and crashes all the application. I do not know why it only works sometimes and it is causing me trouble to figure a solution out. On my controllers I am passing the service that I created to read the file which is appResourcesService:
app.controller('CommonController', ['$scope', '$location', 'appResourcesService',
function ($scope, $location, appResourcesService)
And the service to read resoruces is the following:
'use strict';
app.factory('appResourcesService', ['$resource', function ($resource) {
var appResourcesServiceFactory = {};
appResourcesServiceFactory.getResources = function ($scope, language, locale) {
var languageFilePath = 'resources/AppResources.json';
$resource(languageFilePath).get().$promise.then(function (data) {
$scope.appResources = data;
}, function (reason) {
var defaultLanguageFilePath = 'resources/AppResources.json';
$resource(defaultLanguageFilePath).get(function (data) {
$scope.appResources = data;
});
});
};
return appResourcesServiceFactory;
}]);
Like I said, sometimes it works without any kind of problem, but sometimes when in the controller I reach the piec eof code $scope.appResources, appResources is undefined. I think it is maybe because it reaches there before the file is read, but I am not being able to find a solution to avoid it.
Your factory should return a promise.
It's the job of your controller to handle data. (I use $http as it's cleaner)
app.factory('appResourcesService', ['$http', function($http) {
var appResourcesServiceFactory = {};
appResourcesServiceFactory.getResources = function () {
var languageFilePath = 'resources/AppResources.json';
return $http.get(languageFilePath).then(function(response) {
return response.data;
});
)};
return appResourcesServiceFactory;
}]);
You resolve the promise inside the controller with .then to get the data and set your scope.
appResourcesServiceFactory.getResources().then(function(data) {
$scope.appResources = data;
})
I'm trying to pass data from one controller to another using a service, however no matter what I'm trying it always returns 'undefined' on the second controller. Here is my service :
app.service('myService', ['$rootScope', '$http', function ($rootScope, $http) {
var savedData = {}
this.setData = function (data) {
savedData = data;
console.log('Data saved !', savedData);
}
this.getData = function get() {
console.log('Data used !', savedData);
return this.savedData;
}
}]);
Here is controller1 :
.controller('HomeCtrl', ['$scope','$location','$firebaseSimpleLogin','myService','$cookies','$window', function($scope,$location, $firebaseSimpleLogin, myService, $cookies, $window) {
loginObj.$login('password', {
email: username,
password: password
})
.then(function(user) {
// Success callback
console.log('Authentication successful');
myService.setData(user);
console.log('myservice:', myService.getData()); // works fine
}]);
And then controller2:
// Dashboard controller
.controller('DashboardCtrl', ['$scope','$firebaseSimpleLogin','myService',function($scope,$firebaseSimpleLogin, $location, myService) {
console.log('myservice:', myService.getData()); //returns undefined
}]);
That is simple code, unfortunately I've been struggling for a few hours now, any suggestion ? Thanks.
Created a fiddle here:
http://jsfiddle.net/frishi/8yn3nhfw/16
To isolate the problem, can you remove the dependencies from the definition for myService and see if that makes it work? Look at the console after you load the fiddle.
var app = angular.module('app', [])
.service('myService', function(){
this.getData = function(){
return "got Data";
}
})
I assume the issue is that you are returning this.savedData in the service. Try returning savedData.
this behaves different in Javascript than in other languages.
How can I use the fetched data in customersController in AnotherCustomersController
function customersController($scope, $http) {
$http.get("http://www.w3schools.com//website/Customers_JSON.php")
.success(function(response) {$scope.names = response;});
}
function AnotherCustomersController($scope){
//What should I do here??
}
Full Details Here
You can share data between controllers using $rootscope but I don't think this is a best practice so my solution contain usage of angular service -> plnkr
app.factory('CustomerService', function ($http) {
return {
fetchData: function () {
return $http.get('http://www.w3schools.com//website/Customers_JSON.php')
}
}
});
app.controller('customersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
app.controller('AnotherCustomersController', function ($scope, CustomerService) {
CustomerService.fetchData().success(function (response) {
$scope.names = response;
});
});
Additionally i have refactor your code so only one app is used on page. If you want to use more than one you have to bootstrap them manually -> Read More
I have abstracted my working code from a controller into a factory, but it doesn't seem to be working and I can't find what's wrong. I opted for a factory rather than a service because I wanted to execute some code that defined the variable before returning that variable; I want to get result.station (a part of the data returned by the API), not the full result.
This is my code:
var app = angular.module("myApp", []);
app.factory('api', ['$http',
function($http) {
var station_list = [];
$http({
method: 'GET',
url: 'http://api.irail.be/stations/?format=json&lang=nl'
})
.success(function(result) {
station_list = result.station;
});
return {
Stations: function() {
return station_list;
}
};
}
]);
app.controller("myController", ['api', '$scope',
function(api, $scope) {
$scope.station_list = api.Stations();
$scope.title = "Stations";
}
]);
and a working example.
Try this:
.success(function(result) {
angular.copy(result.station, station_list);
});
You had a small error, you were replacing the array instead of populating it. I used angular.copy instead of the assignment in your factory and it works
http://plnkr.co/edit/sqgKcFZAcClmkfdXHhrz
The problem is that you are dealing with asynchronous nature of AJAX.
I would suggest to have a delegate method in controller, which will be called when the service call is complete.
Something like the following:
app.controller("myController", ['api', '$scope',
function(api, $scope) {
api.Stations( function(station_list) {
$scope.station_list = station_list;
});
$scope.title = "Stations";
}
]);
The following is a service method excerpt:
return {
Stations: function(delegate) {
if (delegate)
delegate(station_list);
return station_list;
}
};