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;
});
}]);
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>
I have this code in a script.js file:
scotchApp.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
scotchApp.controller('SharedController',['$scope', 'myService', function($scope) {
myService.set('hello');
$scope.message = myService.get();
}]);
when I try to upload an html that uses this code I get in chrome (F12 mode):
angular.js:12722 ReferenceError: myService is not defined
why?
You never injected your service into controller. Correct code:
scotchApp.controller('SharedController', ['$scope', 'myService', function($scope, myService) {
myService.set('hello');
$scope.message = myService.get();
}]);
Note controller function signature function($scope, myService) {...}.
Most propbably you have not added service script in index.html
<script src="src/your_path/script.js" ></script>
I need help, about added jasmine tast to my factory.
My code is...
---dataService.js---
angular.module('angularAppApp')
.factory('dataService', function($resource){
return $resource(`http://...:3100/posts/:id`, null,
{
'update': { method:'PUT' }
});
})
---onePostCtrl.js ---
angular.module('angularAppApp')
.controller('onePostCtrl', ['$scope', '$http', '$routeParams', 'dataService',
function ($scope, $http, $routeParams, dataService) {
dataService.get ({id: $routeParams.postId}).$promise.then(function(data){
$scope.postInfo = data;
});
}]);
-- main container ---
angular.module('angularAppApp').controller('postCtrl', ['$scope','$http', 'ngDialog', 'dataService','trimService', function ($scope, $http, ngDialog, dataService, trimService) {
//save data to remote server from loaded pop-up
$scope.savePost = function(){
$scope.addFormData.date = $scope.formated_date;
dataService.save($scope.addFormData, function() {
laodData();
});
ngDialog.closeAll();
};
//delete post from remote server
$scope.deletePost = function(article) {
dataService.delete({ id: article._id }, function() {
laodData();
});
};
//edit post from remote server
$scope.updatePost = function (article) {
dataService.update({ id: article._id},article).$promise.then(function() {
laodData();
});
ngDialog.closeAll();
}
}]);
--- mock data ---
angular.module('mock', []).value('items', [{ ... }]
---At index.html I am have loaded mocks scripts---
src="bower_components/angular-mocks/angular-mocks.js"
src="mosk_data/mocks.module.js"
--Jasmine tests is ...
describe("factory of dataService", function (){
var $httpBackend, $http, $q, factory;
beforeEach(module("angularAppApp"));
beforeEach(module('mock'));
beforeEach(function(){
inject(function($injector, _$httpBackend_,_$http_,_$q_){
$q = _$q_;
$http = _$http_;
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/items').respond(items);
factory = $injector.get('dataService');
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("Data service", function(){
});
});
Now, I have error "ReferenceError: items is not defined" and cannot ideas how I can test my dataService.
You forgot to inject your value and assign it to a variable in the tests. Try this:
var $httpBackend, $http, $q, factory, items; //declare variable items here (or you can do it inside beforeEach)
beforeEach(module("angularAppApp"));
beforeEach(module('mock'));
beforeEach(function(){
inject(function($injector, _$httpBackend_,_$http_,_$q_, _items_){
$q = _$q_;
$http = _$http_;
//inject the value and assign to your variable
items = _items_
$httpBackend = _$httpBackend_;
$httpBackend.when('GET', '/items').respond(items);
factory = $injector.get('dataService');
});
The Reference error you got was because there was no variable called items. You defined an angular value with name items, but it's not the same as a variable - think of it as it lives "somewhere inside angular guts" and to use it you have to inject it and then use as normal variable.
I have an issue communicating from my application to a module i have created. I have create an AngularJS module below.
(function (document, window) {
'use strict';
var piCart = angular.module('piCart', []);
piCart.config(['$routeProvider', function($routeProvider){
$routeProvider.
when('/cart', {
templateUrl: "packages/pi-cart/segments/cart.html",
controller: 'CartController',
private : true
}).
when('/checkout', {
template: "Checkout Page",
// controller: 'CartController',
private : true
});
}]);
piCart.factory('TestFactory', function(){
return{
test : function(){
return 'test works';
}
}
});
piCart.controller("CartController",function(TestFactory){
console.log("Cart Controller Running");
console.log(TestFactory.test());
});
})(document, window);
This is loaded into my main application as so
var app = angular.module('app', ['ngRoute', "ui.bootstrap", "googlechart", "piCart"]);
Im trying to call the module TestFactory from the app.controller like so
app.controller('ProductController',function($scope){
$scope.addToCart = function(id){
//alert("clicked: "+id);
test = TestFactory.test();
console.log(test);
};
});
But im getting the error
ReferenceError: TestFactory is not defined
I believe you're getting that error because you did not inject TestFactory in the controller:
app.controller('ProductController', function($scope, TestFactory) {
// your code...
});
angular.module('app.services', []).service("test", function($http, $rootScope){
this.test=function(){
$rootScope.name="test1";
};
};
angular.module('app.controllers', []).controller('TestController', function ($scope, test) {
test.send();
})
I dont get an error but the changes don't get applied to the UI. I tried $scope.apply() and got an error.
We need to tell Angular which modules your module depends on, In our case the main module is app.controllers.
To call service from different model we need tell to controller where is our service:
['app.services']
JS
var appServices = angular.module('app.services', []);
var appCtrl = angular.module('app.controllers', ['app.services']);
appServices
.service("test", function ($http, $rootScope) {
this.send = function () {
$rootScope.name = "test1";
};
});
appCtrl.controller('TestController', function ($scope, test) {
test.send();
});
Demo Fiddle
I think you should change ".service" by ".factory".
As I can see in the creating services docs there are 3 ways of creating custom services. One of then is using factory way, as the following:
var myModule = angular.module('myModule', []);
myModule.factory('serviceId', function() {
var shinyNewServiceInstance;
//factory function body that constructs shinyNewServiceInstance
return shinyNewServiceInstance;
});
Hope to help.