How can I call the JS function which is defined in subpage? - angularjs

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);
})();

Related

getting service instance in controller

I'm trying to get a service instance but am getting an error. I am getting the exception that Calculator.random() is not a function. Any idea what I'm doing wrong?
angular
.module('app')
.factory('Calculator',function(){
var random = {};
random.number = function (){
return Math.random();
};
return random;
});
angular
.module('app')
.controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.random = Calculator.random();
}]);
You can try like this:
angular
.module('app').controller('homeCtrl', function($scope, Calculator) {
$scope.random=Calculator.number();//in your factory number holds the random function.
}
IN your case its breaking
reason: Calculator.random(); is not a function.
Like Cyril said, you define an object with a local name random in the calculator factory definition. You then return that object but that object has a property called number that points to a function not a property called random.
angular
.module('app', [])
.factory('Calculator',function(){
var random = {};
random.number = function (){
return Math.random();
};
return random;
});
angular
.module('app')
.controller('homeCtrl', ['$scope','Calculator', function ($scope,Calculator) {
$scope.random = Calculator.number();
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">{{random}}</div>
</div>
This should work:
angular
.module('app', [])
.factory('Calculator', function () {
return function () {
return Math.random();
}
});`

I try to pass object from controller to another controller using factory

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":"",
}
});

Updating the scope variable across multiple controllers in angularjs

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

Call function into another function with in the same Controller Angular Js

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();
}
}
}
}

AngularJS Inject factory into another factory from the same module

I'm trying to inject the factory Application into the ApplicationService factory. Both are defined in the same module.
Application factory (application.model.js)
(function(Object, coreModule) {
'use strict';
// the factory to expose that allows the creation of application instances
var ApplicationFactory = function() {
console.log("Application factory!");
return {foo: 'bar'};
}
coreModule.factory('Application', [ApplicationFactory]);
})(Object, angular.module('core'));
ApplicationService factory (application.service.js)
(function(coreModule) {
'use strict';
var ApplicationService = function(Application) {
var api = {
shout = function() {console.log(Application);}
};
return api;
}
ApplicationService.$inject = ['Application'];
coreModule.factory('ApplicationService', [ApplicationService]);
})(angular.module('core'));
Then I'm injecting ApplicationService factory into a controller and calling the method shout. I get undefined when in the console's log, Application is always undefined. If in a controller I innject Application it works. So i know both factories are working standalone.
Both files are being imported in my index.html.
I've spent hours looking for the issue but I can't find it. What am I doing wrong?
Please see working demo below.
You've got 2 options.
a) Remove square brackets here:
coreModule.factory('ApplicationService', ApplicationService)
b) Add injected Application as first element before ApplicationService:
coreModule.factory('ApplicationService', ['Application', ApplicationService])
var app = angular.module('core', []);
app.controller('firstCtrl', function($scope, ApplicationService) {
ApplicationService.shout();
});
(function(Object, coreModule) {
'use strict';
// the factory to expose that allows the creation of application instances
var ApplicationFactory = function() {
console.log("Application factory!");
return {
foo: 'bar'
};
};
coreModule.factory('Application', [ApplicationFactory]);
})(Object, angular.module('core'));
(function(coreModule) {
'use strict';
var ApplicationService = function(Application) {
var api = {
shout: function() {
console.log(Application);
}
};
return api;
};
ApplicationService.$inject = ['Application'];
coreModule.factory('ApplicationService', ApplicationService);
})(angular.module('core'));
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="core">
<div ng-controller="firstCtrl">
</div>
</body>

Resources