I am getting error of service not defined in angular js but I cant figure out why as my controller and module is perfectly connected:
application.js:
var myapp=angular.module('myApp', []);
myapp.service('productService', function() {
var productList = "";
var addProduct = function(newObj) {
productList=newObj;
};
var getProducts = function(){
return productList;
};
return {
addProduct: addProduct,
getProducts: getProducts
};
});
controller1.js:
myapp.controller('contrl1', ['$scope','productService', function ($scope) {
var st="datsat";
productService.addProduct(st);
}]);
Controller 2:
myapp.controller('contrl2', ['$scope','productService', function ($scope) {
$scope.products = productService.getProducts();
}]);
Also in the views I have given link to contoller.js file and application.js file
This is the right way to create your controller:
myapp.controller('contrl2', ['$scope','productService', function ($scope, productService)
When you're using DI and inline array annotation, the annotation array (strings) and function parameters should be synced (the same).
Related
I have created notification factory and pass inside controller,Inside controller when assign the factory to the scope getting error.
alertsManager
MyApp.factory('alertsManager', function() {
return {
alerts: {},
addAlert: function(message, type) {
this.alerts[type] = this.alerts[type] || [];
this.alerts[type].push(message);
},
clearAlerts: function() {
for(var x in this.alerts) {
delete this.alerts[x];
}
}
};
});
var LoginController = function($scope,$rootScope,alerts,alertsManager)
{
$scope.alerts = alertsManager.alerts;
// getting error.
**angular.js:11594 TypeError: Cannot read property 'alerts' of undefined**
}
LoginController.$inject = ['$scope', '$rootScope','alerts','alertsManager'];
**why factory not able to access inside controller.*
Try something like below .
code:
var myApp = angular.module('myApp', []);
myApp.factory('alertsManager', function() {
return {
alerts: {'alert':"i'm from factory service"},
addAlert: function() { //code },
clearAlerts: function() { //code }
}
});
myApp.controller('MyCtrl',['$scope','alertsManager', function($scope, alertsManager) {
$scope.test = alertsManager.alerts.alert;
}]);
Note : Inject factory service into Controller
working sample here .
No need to inject 'alerts' as a dependency in controller.
Sorry ..very stupid question .. Are you sure Do you include these files in Index.html?
like this:
<script src="app/services/alertsManager.js"></script>
im using angularJS v 1.5.6 and want to know how to pass my form data correctly with $location.path.
Here is my code Page A:
<form>
...
<button type="submit" ng-click="submit(formData)">submit</button>
</form>
JS:
app.config(['$routeProvider', function ($routeProvider) {$routeProvider
// Home
.when("/", {
templateUrl: "A.html",
controller: "ACtrl"
})
.when("/B/", {
templateUrl: "B.html",
controller: "BCtrl"
})
//fallback url if nothing matches
.otherwise({
redirectTo: '/'
});
}]);
app.controller('ACtrl', function ( $scope, $location, $http) {
$scope.formData = {};
$scope.submit = function() {
$location.path("/B/" + $scope.formData );
};
});
//controller for B page
app.controller('BCtrl', ['$scope', '$routeParams',
function($scope,$routeParams) {
$scope.formData = $routeParams.formData;
}]);
it is a pretty simple example, but i cant figure out how to solve it :(
By clicking the submit nothing happens. If i remove the $scope from $scope.formData i get a error like: Error: formData is not defined.
The terms in formdata are available, i tested it with console.log($scope.formData) and everything is ok.
here is the link plunker: https://plnkr.co/edit/K5zwcmRRyom5HR4a5Q9o
EDIT
the only issue is now, how to handle the select object correctly in the foreach loop. Need help please
You can do it by creating a service and using setter/getter in order to transfer a variable.
For example like this: https://plnkr.co/edit/IuTXsVLU7dq3TylfnSYP?p=preview
app.service('TransferService', [function(){
var savedData,
service = {
getData: getData,
setData: setData
}
function getData(){
return savedData
}
function setData(data){
savedData = data
}
return service
}])
Don't use location.path...
You could either use a service or use localstorage (or some other browser storage mechanism [sessionStorage, indexdb].
Service Method Below
app.service("SomeService", function () {
var value = null;
this.set = function (val) {
value = val;
return this;
}
this.get = function () {
return value;
}
})
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
SomeService.set($scope.formData);
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
//Check that the data is present in the SomeService service.
var dataFromACtrl = SomeService.get();
if (dataFromACtrl) {
$scope.formData = dataFromACtrl;
}
})();
})
Using localStrorage below, could be sessionStorage.
app.controller("ACtrl", function ($scope, SomeService) {
$scope.formData = {};
$scope.submit = function() {
//Assuming you've populated it with some data...
window.localStorage.setItem("form_data", JSON.stringify($scope.form_data));
$location.path("/B/");
};
})
app.controller("BCtrl", function ($scope, SomeService) {
$scope.formData;
(function () {
var dataFromACtrl = window.localStorage.getItem("form_data");
if (dataFromACtrl) {
$scope.formData = JSON.parse(dataFromACtrl);
}
})();
})
Note
Using the localStorage example you would need to do some clean-up, after doing whatever you want to do with that data in Bctrl you'd want to clear the entry in localstorage using either of the below lines of code:
window.localStorage.removeItem("form_data");
delete window.localStorage["form_data"];
what i need
i need to pass values selected from one controller to another
i have reffer link : Passing data between controllers in Angular JS?
js code
var app = angular.module('myApp', []);
app.service('productService', function() {
var productList = [];
var addProduct = function(newObj) {
productList.push(newObj);
};
var getProducts = function(){
return productList;
};
return {
addProduct: addProduct,
getProducts: getProducts
};
});
app.controller('parentController', function ($scope,productService) {
$scope.change = function () {
alert($scope.value);
}
});
error
error: [$injector:unpr] Unknown provider: productServiceProvider <- productService <- parentController
i need to pass data from controller to another .
whereas i don"t understand why its producing such errors.
This error results from the $injector being unable to resolve a required dependency.
To fix this, make sure the dependency is defined and spelled correctly.
I have two guess for this:
You fix a service name typo, while copy code to your question Fiddle.
Just check your actual service name
You redeclare angular.module Example
Example:
var app = angular.module('myApp', []);
app.service('productService', function() {
return {};
});
app = angular.module('myApp', []); // <- module redeclared
app.controller('parentController', function ($scope,productService) {
$scope.value = 'World'
});
angular.module('myApp', []) creates new instance of module without knowing previous declared providers.
You can retrieve it for subsequent use with angular.module('myApp').
you have declared service before module declearation. so it is not added to your module
follow these steps
var app = angular.module('myApp', []);
then create controllers and service
app.service('productService', function() { ....
and
app.controller('parentController', function ($scope,productService) {...
I have change your fiddle example check Link,
I have created another controller which share same service.
I have code:
angular.module('admin', [])
.provider('users', function () {
this.users = 'default';
this.$get = function () {
var that = this;
return {
getUsers: function () {
return that.users;
}
}
};
})
.run(function (users, $http) {
users.users = $http('url'); // and others
})
.controller('test', function ($scope, users) {
$scope.users = users.getUsers();
});
I would like to intitalize data in .run() method (I can't use .config() method because it doesn't let to pass any services like $http). I found .run() method, but this code doesn't work... Data aren't saved in provider. Official documentation says:
"Execute this function after injector creation. Useful for application initialization."
I think it's best way to initialize data.
You may want to use an Angular Factory/Service for this kind of need. That is what I do. And pass that into the application. That service will be your singleton or source of truth about the dat.
angular.module('myData.services', [])
.factory('myData', ['$rootScope', '$http' , function($rootScope,$http) {
var factory = {
myData : {}
};
$http('/api/call', function(apiData) {
factory.myData = apiData;
});
return factory;
}]);
You could then use this in your controllers:
angular.module('myApp.controllers', [])
.controller('myCtrl', ['myData', '$scope', function(myData, $scope){
$scope.users = myData;
}]);
Check out the documentation on services: https://docs.angularjs.org/guide/services
Second attempt
angular.module('admin', [])
.factory('users', function ($http) {
var users = {};
var data = [];
$http.get('database.php')
.then(function (response) {
data = response.data;
});
users.getData = function () {
return data;
};
return users;
})
.controller('test', function ($scope, users) {
console.log(users.getData());
});
I would like to have data private. Empty Array returned, reponse comes with all data.
Provider configuration can be doable inside config block only, you can't do that inside run block
Though I don't find a reason to load users object while configuring app. I'd say that you should use either service/factory for this.
Code
angular.module('admin', [])
.service('users', function($http, $q) {
var users = [];
//make an get call to fetch users
function getUsers() {
return $http.get('database.php')
.then(function(response) {
data = response.data;
});
}
//will make a call if users aren't there
this.getData = function() {
// Handled below two conditions
// 1. If users aren't fetched the do an Ajax
// 2. If last ajax doesn't return a data then DO it again..
if (users.length > 0)
return $q.resolve(data); //do return data using dummy promise
return getUsers();
};
return users;
})
.controller('test', function($scope, users) {
users.getData().then(function(data){
console.log(data);
});
});
I'm trying to import JSON data into an angularJS application. I split my app into a controller and the import-service, but both in different files. I'm also using bower, grunt and yeoman (that's due to work, I'm not quite used to these, maybe there's also a problem.)
The strange behavior is:
I wanted to retrieve the JSON data with a $http.get() and resolve it - all within a service, so that I can hand out the data object from there to the main controller and won't have to resolve it there.
Strangely, I didn't get any data, it was empty or not readable. Then I handed out the promise which I the $http.get() mehtod gives back and resolved it in the controller. That's not what I wanted, but now it works.... but why?
I guess it's a schmall misstake somehwere but neither me nor my team members can find one. Strangely, doing a little test-app without grunt, yeoman and bower it worked.
I'd appreciate every hint or idea...
Jana
Here's my code from the NOT working version, first the main module with controller:
/** Main module of the application. */
(function () {
'use strict;'
angular.module('angularRegelwerkApp', [])
.controller('RegelwerkCtrl', function ($scope, CategoryFactory) {
$scope.categories = CategoryFactory.getCategories();
$scope.subcategories = CategoryFactory.getSubCategories();
}
);
})();
Service-part:
(function () {
'use strict';
var app = angular.module('angularRegelwerkApp')
.service('CategoryFactory',
function ($http) {
var categories = [];
var subcategories = [];
$http.get("../mockdata/categories.json").then(function (response) {
categories = response.data;
})
$http.get('../mockdata/subcategories.json').then(function (response) {
subcategories = response.data;
})
return {
getCategories: function(){
return categories;
},
getSubCategories: function(){
return subcategories;
}
}
}
);
})();
Here's my code from the WORKING version, first the main module with controller:
/** Main module of the application. */
(function() {
'use strict;'
angular.module('angularRegelwerkApp', [])
.controller('RegelwerkCtrl', function ($scope, CategoryFactory) {
$scope.categories = [];
$scope.subcategories = [];
CategoryFactory.getCategories().then(function(response) {
$scope.categories = response.data;
});
CategoryFactory.getSubCategories().then(function(response) {
$scope.subcategories = response.data;
});
}
);
}
)();
Service-part:
(function () {
'use strict';
var app = angular.module('angularRegelwerkApp')
.service('CategoryFactory',
function ($http, $q) {
var categoryURL = "../mockdata/categories.json";
var subcategoryURL = '../mockdata/subcategories.json';
function getSubCategories() {
return $http.get(subcategoryURL);
}
function getCategories() {
return $http.get(categoryURL);
}
return {
getCategories: getCategories,
getSubCategories: getSubCategories
}
}
);
})();
This is destroying your reference, so loop over the data from the server and push it into the variables you need:
$http.get("../mockdata/categories.json").then(function (response) {
for(var x = 0; x < response.data.length; x++){
categories.push(response.data[x]);
}
});
$http call is by default asynchronous.
So in your first version, when you write like $scope.categories = CategoryFactory.getCategories();
you get empty categories, since by the time you access categories, it may not have been loaded with response data.
your app flows like this -
you load the controller
you call the service
service calls $http
you try to access categories (but data will not be available until response is returned from server)
$http.then loads data to $scope.categories
You are storing your data in Angular primitives and these don't update. instead store all your data in an object and it shoudl work (you'll also need to update controller)
(function () {
'use strict';
var app = angular.module('angularRegelwerkApp')
.service('CategoryFactory',
function ($http) {
var data = {};
$http.get("../mockdata/categories.json").then(function (response) {
data.categories = response.data;
})
$http.get('../mockdata/subcategories.json').then(function (response) {
data.subcategories = response.data;
})
return {
getCategories: function(){
return data.categories;
},
getSubCategories: function(){
return data.subcategories;
}
}
}
);
})();