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>
Related
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).
I am very new to angularjs and am having a hard time trying to figure out this issue.
Basically, we are using a factory to request data for our application. When the factory returns a promise, we were hoping that the data inside the returned promise that was defined in our scope, would be able to be used, but it is only returning as text on the page.
For example: We have defined $scope.name in our controller:
app.controller('AccountController',function($scope,Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
$scope.news.push(data);
});
});
so the factory (getSnapshot) will return something like "Hello {{name}}" from an $http request as follows:
app.factory('Account',function($http) {
return {
getSnapshot : function() {
return $http.get('data.php');
}
}
});
Is it possible to allow the factory to access /use {{name}} from the $scope?
You will need to use internal Angular $interpolate service:
app.controller('AccountController', function($scope, $interpolate, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().success(function(data) {
var text = $interpolate(data)($scope);
$scope.news.push(text);
});
});
Use $q and promises thanks to #dfsq's answer on my post similar to this. Works perfectly.
Here's a plunker.
// Factory method.
app.factory('Account', function($http, $q) {
var data;
return {
getSnapshot: function() {
return data ? $q.when(data) : $http.get('data.json').then(function(response) {
data = response.data;
return data;
})
}
}
});
// Controller method.
app.controller('AccountController', function($scope, Account) {
$scope.name = 'Abby';
$scope.news = [];
Account.getSnapshot().then(function(data) {
$scope.news = data;
});
});
I'm struggling to figure out how to do this. Hope anyone can help :)
I have multiple controllers in my Angular app. Like titleCtrl and SettingsCtrl
I have a service which holds a variable like this:
var myVar = {title: 'test', settings: {color: 'black', font: 'verdana'}};
I'm making a $http.get request to update the "myVar" variable from the server.
The question is, how do I update the $scope.title in titleCtrl and $scope.settings in SettingsCtrl AFTER the http request has finished? I know how to do it in a single controller, but how do I update the $scopes in multiple controllers?
Use a watch on that variable in the service. When its updated, then update your values in controller scope. Here's an example:
Inside your controller, you can watch a var myVar on YourService and when it changes, update a variable called myVarInController with the value it changed to.
$scope.$watch(
// This function returns the value being watched.
function() {
return YourService.myVar;
},
// This is the change listener, called when the value returned above changes
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
$scope.myVarInController = newValue;
}
}
);
Just in you service create a object when you get data from you server copy it to that object, so all your controllers can reference to that object.
Please see here http://plnkr.co/edit/j25GJLTHlzTEVS8HNqcA?p=preview
JS:
var app = angular.module('plunker', []);
app.service('dataSer', function($http) {
var obj = {};
getData = function() {
$http.get("test.json").then(function(response) {
angular.copy(response.data, obj);
});
}
return {
obj: obj,
getData: getData
};
});
app.controller('MainCtrl', function($scope, dataSer) {
$scope.data = dataSer;
$scope.get = function() {
$scope.data.getData()
}
});
app.controller('SecondCtrl', function($scope, dataSer) {
$scope.data = dataSer;
});
HTML:
<div ng-controller="MainCtrl">
<button ng-click="get()">get data</button>
<p>Fist Controller:
<br/>{{ data.obj.title}}</p>
</div>
<div ng-controller="SecondCtrl">
<p>Second Controller:
<br/>{{data.obj.settings}}</p>
</div>
Use both factory and service to pass value to two controllers. This is the only way to pass value
angular.module('mulipleCtrlApp', [])
.service('shareService', function () {
return {
title: 'test',
settings: {
color: 'black',
font: 'verdana'
}
};
})
.controller('titleCtrl', function ($scope, shareService) {
$scope.myVar = shareService;
$scope.testchange = function () {
$scope.myVar.title = 'Completed test';
};
})
.controller('settingCtrl', function ($scope, shareService) {
$scope.myVar = shareService;
});
Egghead Link
Jsfiddler Link example
Make your service return promise object.
Then in controller you can define a success call back to fetch title in one and settings in
another controller once the promise is resolved.
Code to use promises
In your service class:
var factory = {};
var factory.fetchData = function () {
return $http({method: 'GET', url: '/someUrl'});
}
return factory;
In controller 1:
$scope.getData = function(){
factory.fetchData().success(response){
$scope.title = response.title;
}
}
Similarly you can update controller 2, to set settings data.
I've found a better and easier maintainable solution in my opinion. Simply do the following to achieve to-way data-binding between one (or more) controller(s) with a service:
Lets assume you fetch (i.e. $http) and store data in your service (serviceName) in the variable serviceData.
In your controller reference the service like this to achieve to-way data-binding:
$scope.data = serviceName
In your view/html bind to the data properties like this:
<input ng-model="data.serviceData.title">
Thats it! :) When your serviceData variable updates the view/scope does as well. This will work with multiple controllers.
I'm trying to play with angularJS.
I wrote this easy example :
var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});
function FirstCtrl($scope) {
$scope.data = Data;
}
function SecondCtrl($scope) {
$scope.data = Data;
}
but i get the following error message:
ReferenceError: Data is not defined
What am i doing wrong
You're using Data which you never defined in the global scope.
Instead, since you defined it with Angular's dependency injection mechanism:
var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});
// angular will figure it out based on parameter name
myApp.controller("FirstCtrl",function($scope,Data) {
$scope.data = Data;
});
fiddle
var myApp = angular.module('myApp',[]);
myApp.factory( 'Data' , function() {
return { message: "I'm data from a service" }
});
I have a problem with inject controller for broadcast service...
I found this working tutorial
http://jsfiddle.net/simpulton/GeAAB/
but I have a controller encapsulated like this (myApp)
myApp.controller('ControllerZero',
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
});
and my problem is .. I dont know how I can inject controller like at tutorial before
if I put this inject under my controller
ControllerZero.$inject = ['$scope', 'mySharedService'];
this give me back in console:
Uncaught ReferenceError: ControllerZero is not defined
You need to use an array to let angular know all controller variables
myApp.controller('ControllerZero', ['$scope', 'mySharedService',
function ControllerZero($scope, sharedService) {
$scope.handleClick = function(msg) {
sharedService.prepForBroadcast(msg);
};
$scope.$on('handleBroadcast', function() {
$scope.message = sharedService.message;
});
}]);