What is the most simple way to share a method between 2 directives?
I've tried using a factory and injecting that in my directives. But then I can't pass parameters to the factory. So I can get data back from my factory but I can't make the factory dynamic.
.directive('myFirstDirective', [...])
.directive('seconDirective', [...])
.factory('MenuItems', [function(){
return "testString";
}]);
By adding the factory to my code I can do in any directive:
var test = MenuItems;
But what I wan't to do is:
var test = MenuItems(myParameter); //so I can change the return in menuItems depending on myParameter
You can use a service to do that:
https://gist.github.com/anonymous/50b659c72249b58c31bf
.factory('MenuItemsService', [function(){
return {
getMenuItems : function(parameter){
if ( parameter === 'foo' ){
return ['bar', 'jar', 'tar'];
} else {
return ['asd', 'bsd', 'csd'];
}
}
};
}]);
Then in each directive you can inject the service, e.g:
MenuItemsService.getMenuItems('foo');
MenuItemsService.getMenuItems('bar');
To share data creating a service is the right thing to do.
Create a function on your service to process the data
.factory('MenuItems', function(){
var someDataToShare = ...
return {
someFunction: function(data) {
// process data here
return someDataToShare
}
}
});
call it like this:
$scope.processedData = MenuItems.someFunction($scope.someData)
Related
I have a directive and now I want to send same data to other controller's methods and this controller is totally independent of this directive. this other controller is actually resides out the current directory.
How can I do this in angularjs?
Create an angular service and inject in both the controllers. Update a variable in that service from controller 1 and retrieve in controller 2. Something like this -
myApp.factory('myFactory', function () {
// declare and store the value in a local variable here
var prop = '';
return {
getProperty: function () {
return prop;
},
setProperty: function(value) {
prop = value;
}
};
});
function Ctrl1($scope, myFactory) {
myFactory.setProperty('myValue');
}
function Ctrl2($scope, myFactory) {
val = myFactory.getProperty();
}
An angular service is a Singleton, so it maintains the state throughout the code.
In angularjs there is an idea about directive scope.It lets you to use data for directive with 3 ways.
1) string #
2) biDirectional =
3) functional &
I think you have heard about these.This link maybe can help you.
https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object
In the following code i am trying to change to another page on click and want to pass the object i how can i do it. In the following code i get it as undefined.how to go about this
<button ng-href="#/page1" value="{{i.display}}"></button>
app.controller("ctrls",['$scope','$location',function($scope,$location){
$scope.func = function(i) {
$scope.var=i
$location.path("/rel");
};
]);
app.controller("ctrls",'$scope',function($scope) {
console.log($scope.var) //undefined
]);
Pages normally have controller(s), a service can be created to share data between pages ( by injecting service in associated controllers). Like:
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Happy Helping!
Use a service (best) https://docs.angularjs.org/guide/services
Or $rootScope (bad, but simpler) https://docs.angularjs.org/api/ng/service/$rootScope
What is the way to create private methods in an AngularJS controllers?
I have currently done it like this, but I wonder whether it is the correct/preferable way:
app.controller('MyController', function($scope){
myPrivateFunction();
anotherPrivateFunction();
...
$scope.someScopeMethod = function(){
...
anotherPrivateFunction();
...
};
$scope.anotherScopeMethod = function(){
...
myPrivateFunction();
...
};
...
function myPrivateFunction(){
//
}
function anotherPrivateFunction(){
//
}
});
This is correct. Your functions will only be visible inside the scope of your controller constructor function. This is the same for factories and vanilla js where functions declared in functions will only be visible in their parent function context.
In factories it would looks like as below:
.factory('my-factory', function(){
function privareMethodA() {
}
var anotherPrivateMethod = function() {
}
return {
publicMethodA = function() {
},
publicMethodB = function() {
}
};
});
So after you inject your factory into another factory or a controller publicMethodA() and publicMethodB() will be available, but privateMethodA() and anotherPrivatemethod() won't be accessible from outside of this factory.
Accessibility of controllers are similar to your snippet.
So I have a directive that takes in data objects as an argument into the scope. The problem is that I handle all my data in my service layer.
So this is some normal non-directive code:
angular.module('app').factory('appFactory', ['appValues', function(appValues) {
var getStuff = function() { return appValues.stuff; };
}]);
But if want to reuse the factory inside a directive and get appValues as an argument:
angular.module('app').directive('myDir', [function() {
return {
...
scope: {
values: '='
}
....
};
}]);
But this puts it on the scope and not into my data layer. So now I need to send the values object to every function call in my directive factory:
angular.module('app').factory('myDirFactory', [function() {
var getStuff = function(values) { return values.stuff; };
}]);
Is there any good pattern to solve this and keep data in the data-layer and bypass the scope/controller?
Also, the factory will be a singleton shared amongst instances of the directive? How should I solve that then? Create a new injector somehow? Submit to putting lots of data object logic into the controller (which I've been thought not to do)?
It was a while ago, and I guess that a simple soultion is simply to provide an function initialize(value) {... return {...};} and then the returned object has access to the value argument without providing it as a parameter everywhere:
angular.module('myDir').factory('myDirFactory', [function() {
var initialize = function(values) {
var getStuff = function() {
return values;
};
return {
getStuff: getstuff;
};
};
return {
initialize: initialize
};
}]);
Let's assume I have some service and some controller. What that service will return depends of what the controller will pass into it. But is it possible indeed? I suspect a service may look like this:
var app = angular.module('tApp',[])
.provider('getFileContents', function(param){
this.paramId = param;
this.$get = function(){
var par = this.paramId;
return{
getContents:function(){
return "paramId comes here: "+par;
}
}
}
});
then I think my controller should look like this:
app.controller('test_controlController',
function test_controlController($scope,getFileContents){
$scope.contents = getFileContents.getContents('test_control');
console.dir($scope.contents);
});
...but it doesn't work. It says:
Uncaught Error: Unknown provider: param from tApp
So is it possible to make it working?
You are adding a parameter to the service constructor instead to the service function. and you are using a provider instead of a service or factory, you can get some information about the difference between services/factories and providers here:
Angular Service VS Provider VS Factory
Back to your code, make to following changes:
Service:
app.service('FileService', function () {
return {
getFileContents : function (fileID) {
//function logic goes here
console.log(fileID);
}
}
});
Controller:
app.controller('TestController', function ($scope,getFileContents) {
$scope.contents = getFileContents.getFileContents(123);
});
Add a parameter for your getContents method in your service
return{
getContents:function(foo){
return "paramId comes here: "+ foo;
}
}