I am new to using angularjs and i have declared a two functions in controller, and now i want to use one function into another function how can i do that
means if i say function name into another function it says Undefined.
here is the code:
'use strict';
angular.module('customer').controller('Controller', ['$scope', '$state', 'Sservice',
function($scope, $state, Sservice) {
var that = this;
(function getDetails() {
//IMPLEMENTATION
}());
this.function2 = function function2 (id){
//implementation
getDetails(); // says undefined
};
}
]);
.controller('SampleController',function($scope){
$scope.funcA = function(){
$scope.funcB();//scope level function
funcC(); //non scope level function``
}
$scope.funcB = function(){
}
var funcC = function(){
}
});
Worked best for me
var app = angular.module('MyApp', []);
app.controller('MyCtrl',['$scope',function($scope)
{
$scope.functionA=function(){
alert("Inside functionA")
$scope.functionB();
};
$scope.functionB=function(){
alert("Inside functionB");
}
}]);
<!DOCTYPE html>
<html ng-app="MyApp" ng-controller="MyCtrl">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Click to call functionA" ng-click="functionA()">
</body>
</html>
.controller('SampleController',function($scope){
$scope.funcA = function(){
$scope.funcB();//scope level function
funcC(); //non scope level function``
}
$scope.funcB = function(){
}
var funcC = function(){
}
});
I don't know what you're trying to achieve exactly, but you can simply declare your two functions as
function getDetails() {
//IMPLEMENTATION
}
this.function2 = function(id) {
getDetails();
};
You are making things complex. Simply, do like this
'use strict';
angular.module('customer').controller('Controller', ['$scope', '$state', 'Sservice',
function($scope, $state, Sservice) {
function getDetails() {
//IMPLEMENTATION
};
function function2 (id){
//implementation
getDetails(); // says undefined
};
}
]);
Several areas of code are confused in your example above. For a start, function2 is not declared properly.
You've wrapped your getDetails function into what is known as a self-executing anonymous function. This means it is not visible to code outside the SEAF wrapper, including function2. Omit the SEAF wrapper so getDetails is defined when function2 wants to use it.
Finally, you are using Angular but assigning function2 to this on the controller. This is probably not what you wanted to do; functions that you want to expose to the HTML should be attached to $scope, not this.
'use strict';
angular.module('customer').controller('Controller', ['$scope', '$state', 'Sservice',
function($scope, $state, Sservice) {
function getDetails() {
//IMPLEMENTATION
}
$scope.function2 = function(id) {
//implementation
getDetails();
};
}
]);
My these options below could help
'use strict';
angular.module('customer').controller('Controller', ['$scope', '$state', 'Sservice',
function($scope, $state, Sservice) {
function getDetails() {
//IMPLEMENTATION
};
function function2 (id){
//implementation
getDetails(); // says undefined
};
}
]);
or
'use strict';
angular.module('customer').controller('Controller', ['$scope', '$state', 'Sservice',
function($scope, $state, Sservice) {
$scope.getDetails = function() {
//IMPLEMENTATION
};
$scope.function2 = function(id){
//implementation
$scope.getDetails(); // says undefined
};
}
]);
Work fine for me:
{
// define angular module/app
var formApp = angular.module('formApp', []);
// create angular controller and pass in $scope and $http
function formController($scope, $http) {
$scope.sitelist = function(){
$http.get("http://mars.ourgoogle.in/clients/techinfini/customcms/index.php/Ajax/sitelist").then(function(items){
console.log(items.data);
$scope.list = items.data;
});
}
// process the form
$scope.processForm = function() {
$http({
method : 'POST',
url : 'http://mars.ourgoogle.in/clients/techinfini/customcms/index.php/Ajax/angulartest',
data : $.param($scope.formData), // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } // set the headers so angular passing info as form data (not request payload)
}).success(function(data) {
$scope.sitelist();
}
}
}
}
Related
OK, I've built services before but obviously I don't actually know what makes them tick, since I can't seem to debug this ultra-simple service call:
app.js:
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = [];
function dataService() {
console.log("I am the dataService and I am loaded");
var foo = 1;
function getData () {
return 2;
}
}
})();
I see this on-screen: I am Angular and I am working. so Angular is loading.
I see this in console: I am the dataService and I am loaded so the dataService is actually being loaded.
But then the console.log is:
undefined (line 8)
TypeError: dataService.getData is not a function (line 9)
What am I missing?
The previous answers are correct in that your $http injection was wrong, but you are also not attaching your service functions to the service:
function dataService() {
var dataService = this; //get a reference to the service
//attach your functions and variables to the service reference
dataService.foo = 1;
dataService.getData = function() {
return 2;
};
}
An Angular service is very simply an object class. It is also a singleton, meaning it's instantiated only once per run of your app. When the service is instantiated it is very much akin to calling the new operator on your dataService "class":
var $dataService = new dataService();
So, when you inject dataService into your controller, you are actually getting an instance, $dataService, of your dataService "class".
See this blog entry for further reading: https://tylermcginnis.com/angularjs-factory-vs-service-vs-provider-5f426cfe6b8c#.sneoo52nk
You are missing the 2nd parameter $http in the function. The named parameters and the actual parameters in function need to be the same, same order and same number. What happened before is that dataService was being assigned an $http instance and the actual dataService was not injected at all because there was no 3rd parameter to inject it into.
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope, $http, dataService) {
// ----was missing-----^
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
We have missed the second param '$http' in function. Just add the '$http' param, it should work fine
var gridApp = angular.module('gridApp', []);
gridApp.controller('mainController', ['$scope', '$http', 'dataService',
function($scope,$http, dataService) {
$scope.message = 'I am Angular and I am working.';
var init = function(){
console.log(dataService.foo);
console.log(dataService.getData());
};
init();
}]);
This is how I've been taught to set up services:
function dataService() {
var dataService = {};
var _foo = 1;
var _getData = function () { return 2; }
dataService.foo = _foo;
dataService.getData = _getData;
return dataService;
}
I believe this facilitates public/private methods/vars.
For reference, this is the full code accessing my service:
app.js:
var gridApp = angular.module('gridApp', []);
// create the controller and inject Angular's $scope
gridApp.controller('mainController', ['$scope', 'dataService', function($scope, dataService) {
// create a message to display in our view
$scope.message = 'Angular is working';
var init = function(){
getPackageData();
};
var getPackageData = function (){
return dataService.getData().then(
function successCallback(response) {
console.log(response);
},
function errorCallback(response) {
console.log(response);
}
);
};
init();
}]);
dataService.js:
(function() {
'use strict';
angular
.module('gridApp')
.service('dataService', dataService)
dataService.$inject = ['$http'];
function dataService($http) {
var dataService = {};
var _getData = function () {
return $http({
method: 'GET',
url: 'data/packages.json'
})
.then(function successCallback(response) {
return response;
},
function errorCallback(response) {
return response;
});
}
dataService.getData = _getData;
return dataService;
}
})();
I'm having an issue correctly getting a data service to work as I try to follow the Angular Style Guide (https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#data-services)
I'm sure it's something obvious to the more experienced but I can't get the data set to assign properly to the vm.items outside of the
Data Service
(function() {
'use strict';
angular
.module('portfolioApp')
.factory('portfolioService', portfolioService);
portfolioService.$inject = ['$http', 'logger'];
function portfolioService($http, logger) {
return {
getPortfolioData: getPortfolioData,
};
function getPortfolioData() {
return $http.get('./assets/portfolio/portfolioItems.json')
.then(getPortfolioDataComplete)
.catch(getPortfolioDataFail);
function getPortfolioDataComplete(response) {
return response.data;
}
function getPortfolioDataFail(error) {
logger.error('XHR Failed for getPortfolioData.' + error.data);
}
}
}
}());
Controller
.controller('portfolioController', ['$scope', '$http', '$stateParams', 'logger', 'portfolioService', function($scope, $http, $stateParams, logger, portfolioService) {
var vm = this;
vm.items = [];
activate();
function activate() {
return getData().then(function() {
logger.info('Activate the portfolio view');
});
}
function getData() {
return portfolioService.getPortfolioData()
.then(function(data) {
vm.items = data;
return vm.items;
});
}
console.log("test")
console.log(vm.items);
console.log("test")
}])
Your getData function is a promise, so it's run asynchronously. Your console.log are called before the end of the promise so the vm.items is still empty.
Try to put the log in the then callback.
In angularjs,I use the directive to contains the subpage into mainpage.
However, I found when I want to call the JS function in subpage, the browser always return back the information .
I wonder what can I do to fixed the errors.
Mainpage
var menuModule = angular.module('menuModule',[]);
menuModule.controller("MenuSettingController", function($scope, $http) {
initTree();
});
Subpage
<script type="text/javascript">
function initTree(){
console.log("in");
}
</script>
Thanks a lot.
If you want to call a function which are defined in subpage, you can wrap it into the current window object. Moreover, you can also wrap object into your window object.
Then, you can call your function, into your controllers for example.
Wrap function
Controller
(function(){
function Controller($scope) {
initTree();
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Subpage
<script type="text/javascript">
(function(){
function init(){
console.log('init');
}
//Wrap our init function into our window object
window.initTree = init;
})();
</script>
Wrap object
But, as i said, you can wrap object to the window object, so you can do :
Controller
(function(){
function Controller($scope) {
//Call our init function
app_function.init();
//Call our setter
app_function.set(42);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
Subpage
<script type="text/javascript">
//initialize our anonymous function with the app_function or an empty object
(function(app){
function init(){
console.log('init');
}
function set(n){
console.log('Set value : ' + n);
}
//Register our function
app.init = init;
app.set = set;
})(window.app_function = window.app_function || {});
</script>
Use angular services
Use angular services is a good practice, it will make your code more reusable and clean.
You have to know that all angular services are singletons. So, you can easily share common logic, data between controller.
Controller
(function(){
function Controller($scope, Service) {
//Call our init function
Service.init();
//Call our setter
Service.set(42);
}
angular
.module('app', [])
.controller('ctrl', Controller);
})();
(function(){
function Controller2($scope, Service) {
var old = Service.get();
//Retrieve 42
console.log(old);
//Call our init function
Service.init();
//Call our setter with new value
Service.set(++old);
var newValue = Service.get();
//Retrieve 43
console.log(newValue);
}
angular
.module('app')
.controller('ctrl2', Controller2);
})();
Service
(function(){
function Service() {
var data;
function init(){
console.log('init');
}
function get(){
return data;
}
function set(n){
data = n;
console.log('Set value : ' + n);
}
//Create our object with several method
var factory = {
set: set,
init: init,
get: get
};
return factory;
}
angular
.module('app')
.factory('Service', Service);
})();
I try to call an method of civilitiyController in CustomerController. So, with my search I have found the event's manager to call method but I don't success to return the result from CivilityController to CustomerController.
I already tried this:
1/
civilitiesController :
$scope.$on("getListCivilities", function(event, args){
$scope.civilities = getCivilitiesList();
});
customersController :
$scope.$broadcast("getListCivilities");
console.dir($scope.civilities) // after run civilities = undefined
2/CivilitiesController:
$scope.$on("getListCivilities" , function(event, args){
var list = getCivilitiesList();
return list;
});
CustomersController :
$scope.civilities = $scope.$broadcast("getListCivilities");
console.dir($scope.civilities); //display var of broadcast
3/ Edit:
After first answer, I tried this :
civilities controller :
function getCivilitiesList()
{
var reqGetCivilities = $http({ url: 'api/Civilities/Get' });
reqGetCivilities.success(function(data){
$scope.civilities = data;
$scope.$broadcast("getListCivilities", { list: $scope.civilities });
return data;
});
}
getCivilitiesList();
customersController :
function test()
{
$scope.$on("getListCivilities", function (event, args) {
$scope.civilities = args.list;
console.log('test0');
console.dir($scope.civilities);
});
}
test();
$scope.$on is never executed and I don't see why.
I hope someone can help me.
check this plunker
app.controller('Controller1', function($scope) {
$scope.name = 'World';
$scope.$on('ValueUpdated', function(event, args) {
$scope.name = args.currentValue;
});
});
app.controller('Controller2', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.myData = "type here";
$scope.broadCast = function() {
$rootScope.$broadcast('ValueUpdated', {
currentValue: $scope.myData
});
}
I used broadcast, but you can do this with services and watchers too.
I guess below should work :
function CivilitiesController($scope)
{
$scope.$on('someEvent', function(event, args) {});
// another controller or even directive
}
function CustomersController($scope)
{
$scope.$emit('someEvent', args);
}
JSFiddle (for more details) : http://jsfiddle.net/nikdtu/moo89kaw/
Ahmet Zeytindalı, this is my entire CivilitiesController :
(function () {
'use strict';
'use strict';
angular
.module('LSapp')
.controller('CivilitiesCtrl', CivilitiesCtrl)
CivilitiesCtrl.$inject = ['$scope', '$http', '$rootScope'];
function CivilitiesCtrl($scope, $http, $rootScope) {
function getCivilitiesList()
{
var reqGetCivilities = $http({ url: 'api/Civilities/Get' });
reqGetCivilities.success(function(data){
$scope.civilities = data;
});
}
getCivilitiesList();
function getList()
{
$rootScope.$broadcast("getListCivilities", { list: $scope.civilities });
}
getList();
}
})();
And the method to retreive list:
(function () {
'use strict';
angular
.module('LSapp')
.controller('CustomersCtrl', CustomersCtrl)
CustomersCtrl.$inject = ['$scope', '$http', '$location', '$modal', '$window', '$compile','$cookies', '$state','locker','$q','$timeout', '$rootScope'];
function CustomersCtrl($scope, $http, $location, $modal, $window, $compile, $cookies, $state, locker, $q, $timeout) {
//some code
function test()
{
$scope.$on("getListCivilities", function (event, args) {
$scope.civilities = args.list;
console.log('$on args : ');
console.dir(args);
});
}
test();
}
});
The method $on doesn't run and if I put console.log($scope.civilities) after the method, the result is always undefined.
I try to pass object from index.html controller(signupCtrl) to connexion.html (controller:affCtrl)and display the object in the form of connexion.html using a factory, I created this plunker
This is the script.js file that contains two controllers
'use strict'
var demoApp = angular.module('demoApp', []);
demoApp.controller('signupCtrl', function($scope, $rootScope, per) {
$scope.envoie = function (user) {
per = user;
console.log(per);
window.location="connexion.html"
};
});
demoApp.controller('affCtrl', function($rootScope, per) {
$rootScope.per = per;
});
And the factory:
demoApp.factory("per",function() {
return {
"name":"",
"password":"",
}
});