Calling controller functions within module - angularjs

I have defined a function within my controller, which i want to call in a module. How is this possible?
The controller:
var App = angular.module('App',['ngResource','App.filters']);
App.controller('ExerciseCtrl', ['$scope','$http', function($scope, $http) {
$scope.toggleOn = function (arr, id) {
// Some code
};
}]);
And the module:
angular.module('App.filters', []).filter('someFilter', [function () {
return function () {
someArray = [];
toggleOn(someArray, 1); // Wish to call this function
};
}]);
I want to call toggleOn within the module.

Off the top of my head, maybe something like this:
var App = angular.module('App',['ngResource','App.filters']);
App.service('toggleService', function(){
var service = {
toggleOn: function(arr, id){
}
};
return service;
});
App.controller('ExerciseCtrl', ['$scope','$http', 'toggleService', function($scope, $http, toggleService) {
$scope.toggleOn = toggleService.toggleOn;
}]);
angular.module('App.filters', []).filter('someFilter', ['toggleService', function (toggleService) {
return function () {
someArray = [];
toggleService.toggleOn(someArray, 1); // Wish to call this function
};
}]);

angular.module('App.filters', []).filter('someFilter', [function () {
return function (scope) {
someArray = [];
scope.toggleOn(someArray, 1); // Wish to call this function
};
}]);
And pass scope to filter
<span ng-controller="ExerciseCtrl">{{someFilter | this}}</span>

Related

Angular service and injecting the values

I have an angular app and I want to retain some values between controllers using angular service
Here is my base controller:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
})();
Now I want to add a service I can later fill with key-value pair data. So I tried adding the following:
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
and now it looks like this:
(function () {
var app = angular.module("MyApp", ["ui.router"]);
app.controller("BaseCtrl", ["$scope", "$http", "$state", BaseControllerFunc]);
function BaseControllerFunc($scope, $http, $state) {
....
}
app.service("DataService", function () {
var data_item = {};
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
});
})();
Here I am stuck. How would I go about injecting values (MyKey and MyValue) into my service? I am newbie with Angular so that makes it hard
Try adding functions to handle your data.
app.service("DataService", function () {
var myData = [];
function addItem(key, value){
var data_item = {Key: key, Value: value);
myData.push(data_item);
}
function getData(){
return myData;
}
return {
add: addItem,
get: getData
}
});
In your controller, use it like
DataService.add('key', 'value');
DataService.get();
change it to
app.service("DataService", function () {
var data_item = {};
return{
function somename(MyKey,MyValue){
data_item.Key =MyKey;
data_item.Value=MyValue;
this.MyData.push(data_item);
}
}
});
and from your controller call it as
DataDervice.somename(MyKey,MyValue)

Angular can not find my factory

So I created with angular a small factory to get my local json file now I wanna pass that data to my controller but it can't find the factory name and says 'unresolved variable'.
Here is the snippet of my code what I guess is relevant for now.
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
});
})();
My goal is just to console log the $scope.teams, than I can do more with the data.
you should include "dataFactory" inside your controller
(function () {
var app = angular.module('locatieTool', ['ngRoute']);
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});
// factory
app.factory('dataFactory', function($http) {
var team = {};
//get local data
team.getTeams = function() {
return $http.get ('http://localhost:4040/');
};
return team;
}); })();
I believe you need to pass your factory into the controller:
app.controller('teamController', function ($scope, dataFactory) {
function init () {
dataFactory.getTeams().success(function(data) {
$scope.teams = data
});
}
init();
console.log($scope.teams);
});

How to call a controller function from a service?

i have 2 controllers who are not in the same scope or have a parent child relation.
So i want to call from controlleB a function in ControllerA. In my case its a listContoller with an addItem function and i want to call this function from a addItemController somewhere else on the page after clicking submit. i know this should work with a service, but i dont know how.
app.controller("listCtrl", ["$scope", "listSvc", function ($scope, listSvc){
$scope.list.data = listSvc.load("category");
$scope.addItem = function(newitem) {
$scope.list.data.unshift(newitem);
...
}
}]);
app.controller("addItemCrtl", ["$scope", "listSvc", function ($scope, listSvc){
$scope.addItem = function() {
listSvc.addItem($scope.newItem);
}
}]);
app.service('listSvc', function() {
return{
load: function(section){
...
},
addItem: function(item){
addItem(item); <<-- call function in listController
}
}
});
UPDATE
k is this better? i put the list.data inside my service and i watch from my controller if the list change and put it on the scope from my controller that ng-repeat can do his work... is this appraoch better? or have someone better tips for me how i should do this...
app.service('listSvc', ['$http', function($http) {
var list = {};
return {
list:{
get: function () {
return list.data;
},
set: function (data) {
list.data = data;
}
},
addItem: function(item){
var response = $http.post("/api/album/"+$scope.list.section, item);
response.success(function(){
list.data.unshift(item);
console.log("yeah success added item");
}).error(function(){
console.log("buuuh something went wrong");
});
return response;
},
load: function(section){
var response = $http.get("/api/album/"+section);
response.success(function(data){
list.set(data);
list.section = section;
console.log("yeah success loaded list");
}).error(function(){
console.log("buuuh something went wrong");
});
return response;
}
};
}]);
and in my controllers i do this
app.controller("listCrtl", ["$scope", "listSvc", function ($scope, listSvc){
listSvc.load("category");
...
$scope.$watch('listSvc.list.get()', function(data) {
$scope.list.data = data;
});
...
}]);
app.controller("addItemCrtl", ["$scope", "listSvc", function ($scope, listSvc){
...
$scope.addItem = function() {
listSvc.addItem($scope.newItem);
}
...
}]);
gregor ;)
I just solved this myself! Perhaps this may help:
The function inside of my Controller:
var timeoutMsg = function() {
vm.$parent.notification = false;
};
The function inside my Service (I had to pass in $timeout as well as the name of the function from my Controller, now it works):
// original broken code:
// this.modalSend = function(vm) {
// fixed:
this.modalSend = function(vm, $timeout, timeoutMsg) {
vm.$parent.sendTransaction = function() {
// Show notification
vm.$parent.message = 'Transaction sent!';
vm.$parent.notification = true;
$timeout(timeoutMsg, 4000);
// original broken code:
// $timeout(timeoutMsg(), 4000);
};
}
var vm = $scope

AngularJS - factory is an empty object

I'm new in AngularJS - I can't figure out why I get the error mainDataService.refreshStatus is not a function in the $scope.clickMe function. I see the mainDataService variable is an empty object besides its initialization. What am I doing wrong here ?
var mainDataService = {};
var firstModule = angular.module('myModule', ['ngRoute', 'ngAnimate']);
(function () {
var mainDataServiceInjectParams = ['$http', '$q'];
var mainFactory = function ($http, $q) {
mainDataService.refreshStatus = function (id) {
return $http.get('/api/values/' + id).then(function (results) {
return results.data;
});
};
return mainDataService;
};
mainFactory.$inject = mainDataServiceInjectParams;
firstModule = firstModule.factory('mainService', mainFactory);
}());
firstModule.controller('myCtrl', function ($scope, $http) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainDataService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
You need to use the dependency injection mechanism to load your own services.
Put the mainDataService declaration in a local scope and inject the mainService into myCtrl:
var firstModule = angular.module('myModule', ['ngRoute', 'ngAnimate']);
(function () {
var mainDataServiceInjectParams = ['$http', '$q'];
var mainFactory = function ($http, $q) {
var mainDataService = {};
mainDataService.refreshStatus = function (id) {
return $http.get('/api/values/' + id).then(function (results) {
return results.data;
});
};
return mainDataService;
};
mainFactory.$inject = mainDataServiceInjectParams;
firstModule = firstModule.factory('mainService', mainFactory);
}());
firstModule.controller('myCtrl', function ($scope, $http, mainService) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
Even better, you should explicitly assign the dependencies into the controller, so that your code still works after minifcation (as you already did it for the service):
firstModule.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope', '$http', 'mainService'];
function myCtrl($scope, $http, mainService) {
$scope.TST = '1';
$scope.clickMe = function (id) {
mainService.refreshStatus(id).then(function (results) {
$scope.TST = results;
});
}
});
As you see, if you use normal function definitions, you can make use the function hoisting of Javascript and write the functions at the end while having the relevant code at the top. It's the other way round as in your example of the service.
Supply mainService to controller
firstModule.controller('myCtrl', function ($scope, $http, mainService) {
and then use it in the function
mainService.refreshStatus
I think you immediately invoked function is not invoked so mainDataService still reference the object you set at the first line
(function(){})()
rather than
(function(){}())

Jasmine Test: How to mock a method inside a controller in AngularJS

I am using angularjs and my controller looks like this:
(function (app) {
var myController = function ($scope, myService) {
var onData = function (response) {
if (!response.data || response.data.length === 0) {
app.showErrorMessage('Error');
} else {
$scope.myData = response.data;
drawChart();
}
$scope.loading = false;
};
var init = function () {
$scope.loading = true;
myService.getContBreakdown().then(onData, onError);
};
var drawChart = function () {
// Some Code
};
init();
};
app.controller('myController', ['$scope', 'myService', myController]);
}(angular.module('app')));
I am writing a jasmine test suit to test the data received from the myService, and mock the call to drawChart() method. How should I write the a simple jasmine test suit to mock the call to the drawChart() method?
Your methods should be in the $scope.
It should somehow look like this:
In your Controller:
...
$scope.methodToTest = function () {
...
$scope.methodToMock();
...
}
$scope.methodToMock = function () {
// do something
}
...
In your test:
...
describe( 'methodToTest', function ()
{
it( 'should call the methodToMock', function() {
spyOn( $scope, 'methodToMock' );
$scope.methodToTest();
expect( $scope.methodToMock ).toHaveBeenCalled();
} );
} );
...
Maybe this can help you too:
http://www.benlesh.com/2013/05/angularjs-unit-testing-controllers.html

Resources