How to get data from controller to Factory in angularjs - javascript

I am newbie to Angularjs World. I want to fetch some data from angularjs controller to Angularjs Factory.Controller and factory are defined in different js files.
code from Factory(File name Application.js)
var app=angular.module('myApp',[])
app.factory('autoCompleteDataService', [function(MyController) {
return {
getSource: function() {
return MyController.getFirstName();
}
}
}]);
app.directive('autoComplete', function(autoCompleteDataService) {
return {
restrict: 'A',
link: function(scope, elem, attr, ctrl) {
$(elem).autocompleteArray(autoCompleteDataService.getSource(), {
minLength: 2
});
}
}})
Controller code (File Name Controller.js)
function MyController($scope){
this.getFirstName= function ()
{
var arrayFName=[];
for(var k=0;k< $scope.MyData.length;k++)
{
arrayFName.push($scope.MyData[k].fname);
}
return arrayFName;
}
MyData is array containing some hard coded value for 'fname'
When i ran this code got error 'Error: MyController is undefined'. Is it possible to fetch data from controller if yes then how?

You should have source, or firstName, defined in the factory, and then set it from the controller. It will then be accessible from other controllers which use the factory.
var app=angular.module('myApp',[])
app.factory('autoCompleteDataService', [function () {
var _source;
return {
getSource: function () {
return _source;
},
setSource: function (source) {
_source = source;
}
}
}]);
And then subsequent controllers might be like:
app.controller('someController', ['$scope', 'autoCompleteDataService',
function ($scope, autoCompleteDataService) {
$scope.source = autoCompleteDataService.getSource();
// or even...
// $scope.getFirstName = autoCompleteDataService.getSource;
}]);

Related

AngularJS: Bind a directive to a Controller via a Service update

How to bind a directive to a controller via a service update ?
I want to create the possibility to update a cart(the service) via a directive(add to cart button) and then the controller (that display the cart) will update its view.
Despite the fact that I added a watch on the service itself my controller is not been updated.
Of course it will be good if the controller and the directive doesn't share the same scope (transclude: true in the directive)
The service:
angular.module('stamModule', [])
.factory('valueService', function () {
var factory = {
data: {value: 1000},
inc: inc,
getData: getData
};
function inc() {
this.data.value++;
}
function getData() {
return this.data;
}
return factory;
})
the directive:
.directive('buttonDirective', function (valueService) {
var directive = {
restrict: 'E',
template: '<button>Inc</button>',
link: linkFnc
};
function linkFnc(scope, el) {
el.on('click', function () {
valueService.inc();
});
}
return directive;
})
The controller:
.controller('FirstController', function ($scope, valueService) {
var vm = this;
vm.serv = valueService;
$scope.$watch('vm.serv.getData()', function (newValue) {
console.log("watch");
console.log(newValue);
});
})
The html:
<body ng-app="stamModule">
<hr>
<div ng-controller="FirstController as vm">
<p>{{vm.serv.data}}</p>
<button-directive ></button-directive>
</div>
here's a demo:
https://jsfiddle.net/07tp4d03/1/
Thanks
All your code needed was a little push. No need for event broadcasting or anything like that.
The problem was, that the click event listener was working outside Angular's digest loop, and thus Angular watch wasn't working for you.
If you change your directive's code to the following, it will work.
.directive('buttonDirective', function (valueService) {
var directive = {
restrict: 'E',
template: '<button ng-click="inc()">Inc</button>',
link: linkFnc
};
function linkFnc(scope) {
scope.inc = function() {
valueService.inc();
};
}
return directive;
})
Here is a fork of your fiddle that works

Undefined function in AngularJS directive unit test

I am trying to write a unit test for the toggleDetails function defined inside the following AngularJS directive:
angular.module('hadoopApp.cluster.cluster-directive', [])
.directive('cluster', [function() {
return {
templateUrl:'components/cluster/cluster.html',
restrict: 'E',
replace: true,
scope: {
clusterData: '=',
showDetails: '='
},
link: function(scope, element, attrs) {
scope.toggleDetails = function() {
console.log('Test');
scope.showDetails = !scope.showDetails;
};
},
// Default options
compile: function(tElement, tAttrs){
if (!tAttrs.showDetails) { tAttrs.showDetails = 'false'; }
}
};
}]);
And this is the unit test:
'use strict';
describe('hadoopApp.cluster module', function() {
// Given
beforeEach(module('hadoopApp.cluster.cluster-directive'));
var compile, mockBackend, rootScope;
beforeEach(inject(function($compile, $httpBackend, $rootScope) {
compile = $compile;
mockBackend = $httpBackend;
rootScope = $rootScope;
}));
var dummyCluster;
beforeEach(function() {
dummyCluster = {
id:"189",
name:"hadoop-189",
exitStatus:0
};
mockBackend.expectGET('components/cluster/cluster.html').respond(
'<div><div ng-bind="clusterData.name"></div></div>');
});
it('should toggle cluster details info', function() {
var scope = rootScope.$new();
scope.clusterData = dummyCluster;
// When
var element = compile('<cluster' +
' cluster-data="clusterData" />')(scope);
scope.$digest();
mockBackend.flush();
// Then
var compiledElementScope = element.isolateScope();
expect(compiledElementScope.showDetails).toEqual(false);
// When
console.log(compiledElementScope);
compiledElementScope.toggleDetails();
// Then
expect(compiledElementScope.showDetails).toEqual(true);
});
afterEach(function() {
mockBackend.verifyNoOutstandingExpectation();
mockBackend.verifyNoOutstandingRequest();
});
});
The test fails when calling compiledElementScope.toggleDetails() because the toggleDetails function is undefined:
TypeError: undefined is not a function
Printing the content of the isolated scope inside compiledElementScope I can see that in fact the function is not included in the object.
So, it looks like the toggleDetails function is not included in the isolated scope but I don't know why.
If you use the compile function within a directive, the link function is ignored. You should return the function within the compile method:
compile: function (tElement, tAttrs) {
if (!tAttrs.showDetails) {
tAttrs.showDetails = 'false';
}
return {
post: function (scope, element, attrs) {
console.log('Test');
scope.toggleDetails = function () {
console.log('Test');
scope.showDetails = !scope.showDetails;
};
}
};
}
Also, in order to make the test work, you should add:
scope.showDetails = false;
And the binding to the directive (because you require two values):
var element = compile('<cluster' +
' cluster-data="clusterData" show-details="showDetails" />')(scope);
Jsfiddle: http://jsfiddle.net/phu7sboz/

angular directive ng-repeat scope and Service

I am trying to create angular directive whom can run alone without a Controller, so I can set it anywhere I want, without adding the model to the controller.
The code is fairly simple:
App.directive('ngdPriceWithCurrencySelect',['CurrenciesService' ,function (CurrenciesService) {
return {
restrict: 'E',
replace: true,
scope: true,
link: function ($scope, $element, $attrs) {
$scope.currencies = CurrenciesService.getData();
$scope.$watch('currencies', function(newValue, oldValue){
console.log($scope.currencies);
});
},
template: '<select>\n\
<option ng-repeat="currency in currencies">{{currency.cur_name_he}}</option>\n\
</select>'
}
}]);
The Service actually return the data and the console.log($scope.currencies) shows object with the currencies.
but the repeater is not runing and I am not getting the result I want.
I thought this might be a scope problem, but I can't find a way to see the scope itsel. (angularjs batarang is not working in version 1.3+)
the problem can be in the Service as well so I am giving the service code:
App.service('CurrenciesService', ["$http", "$q", function ($http, $q) {
var service = {
returnedData: [],
dataLoaded: {},
getData: function (forceRefresh) {
var deferred = $q.defer();
if (!service.dataLoaded.genericData || forceRefresh){
$http.get("data/currencies").success(function (data) {
angular.copy(data, service.returnedData)
service.dataLoaded.genericData = true;
deferred.resolve(service.returnedData);
});
}
else{
deferred.resolve(service.returnedData);
}
return deferred.promise;
},
};
service.getData();
return service;
}]);
here is a JS fiddle for testing it: http://jsfiddle.net/60c0305v/2/
Your service returns a promise, not the data itself. You need to set a function for when the service resolves the promise:
link: function ($scope, $element, $attrs) {
// waiting for the service to resolve the promise by using the done method
CurrenciesService.getData().then(function(data) {
$scope.currencies = data;
});
$scope.$watch('currencies', function(newValue, oldValue){
console.log($scope.currencies);
});
}
Check this fiddle

angularjs: access controller of directive

I'm unit testing one of my directives. Its basic structure is like this
angular.module('MyApp')
.directive('barFoo', function () {
return {
restrict: 'E',
scope: {},
controller: function ($scope, $element) {
this.checkSomething = function() { .... }
},
link: function(scope, element) { .... }
}
});
In my unit test I want to test the function 'checkSomething', so I tried
var element = $compile('<barFoo></barFoo>')(scope);
var controller = element.controller()
...
However, controller is undefined. Is it possible to access the controller of the directive ?
the glue is your scope so you can do
controller: function ($scope, $element) {
this.checkSomething = function() { .... }
$scope.controller = this;
},
but i think it would be best practice to attach every function to the scope like
controller: function ($scope, $element) {
$scope.checkSomething = function() { .... }
},
and then its
var element = $compile('<barFoo></barFoo>')(scope);
var checksomthingResult = scope.checkSomething ()

AngularJS communication between controller and directive

How to get some data from controller and use it inside directive thats not a problem.
But I stack with such situation when I need get data from directive and use it in my controller.
For exmpl:
My controller:
function MyController($scope, $location, myDirective) {
"use strict";
// here i need use scope.importantValue and create() method from directive
}
My directive:
.directive("myDirective", function() {
"use strict";
return {
restrict: 'A',
template: '<div></div>',
replace: true,
scope: {
data: '=',
},
link: function(scope, elm) {
scope.importantValue = "value";
function create() {
console.log("Directive works...");
}
};
})
How I can use variables or/and methods from directive inside my controller?
The simplest way to accomplish this is to make both your controller and directive get importantValue and create() from a service.
angular.module(/* Your module */).service('sharedData', function () {
return {
importantValue: "value",
create: function () {
console.log("Directive works...");
}
};
});
Now you can inject sharedData into your directive and controller and access importantValue and create() from either place.

Categories