AngularJS call function from a directive in a different file - angularjs

At first I searched a lot about this question, used some suggestions but couldn't get results.
I had one js file, main.js, where there was only one controller and everything worked fine:
var app = angular.module('monitoringApp', ['ui.bootstrap', 'ngCookies', 'angularCharts','angularUtils.directives.dirPagination','ngLoadScript','ngRoute','dragtable']);
app.controller('mainController', ['$scope', '$http', '$cookies', '$cookieStore' , '$location', function($scope, $http, $cookies, $cookieStore,$location) {
//some function which i need to call;
}
I've added a library for drag and drop table columns dragtable.js and inside dragEnd() function I want to call some function inside main.js
var project = angular.module("dragtable", []);
project.directive('draggable', function($window, $document) {
function dragEnd($event) { need to call function inside main.js }
}
Please note that I already tried to use shared service but still getting error undefined on the function which is called.

It doesn't really matter in which file you're storing the functions. That said, a directive is unlikely to be what you're looking for as a directive is mainly used to be linked to an html element like a widget. Think of it as the controller in the MVC model scheme. It where you can have interaction from/to the ui from the coding standing point. But you can't really call a directive function directly if you don't have access to a directive.
A service on the other hand is just a singleton object that can be injected in a controller or in other places.
What you want is probably this:
project.factory('draggable', function () {
function dragEnd($event) { ... }
return dragEnd
})
And inside your main module:
app.controller('mainController',
[
'$scope'
, '$http'
, '$cookies'
, '$cookieStore'
, '$location'
, 'draggable'
, function(
$scope
, $http
, $cookies
, $cookieStore
, $location
, draggable
) {
//here you can call draggable
}]
)
Here you can see that the draggable function aka dragEnd is injected in the controller. This is good if you want to use this common function for multiple handler but then you might need to bind the function to an object like this:
var draggable = draggable.bind(someobj)
Or use it with apply or call
draggable.call(someobj, event)
draggable.apply(someobj, [event])
The reason to do that is that if you want to acces this from within the function when it's called, it might not be what it you expect it to be depending on how you're actually calling the method.
Also one note regarding your directive... You always have to return something. In you case chances are that you created the factory but didn't return anything. For this reason you had the "undefined" error. If you don'T return anything the factory will create and delete the function when it's run.

Related

How to use module function inside another factory in angularjs

I have configurations.js file which having
var configurationModule = angular.module('configuration', ['restangular', 'notification']);
configurationModule.factory('clientConfigSvc', function (notificationMgr, $interpolate, $injector) {
function getConfig(configKey) {
return getNestedPropertiesByString(activeEnvironment, configKey);
}
}
and having another javascript file with below code
angular.module('ds.coupons').factory('CouponsREST', ['Restangular', 'SiteConfigSvc', 'settings',function (Restangular, siteConfig, settings, configurationModule) {
configSvc.getConfig('services.baseUrl'); /// need to call this function
}
Actually i want function configSvc.getConfig inside second angular factory
Yes After tired of trying lots of solution, today morning working on moving train got idea to fix, dont know if its correct way but its working. but still looking for correct fix if mine was not correct as per angularjs practise.
Here is my solution.
1. I added configuration module in app.js alogn with other
window.app = angular.module('ds.app', [
'restangular',
'ui.select',
'ui.router',
'ds.shared',
'ds.utils',
'ds.i18n',
'configuration']);
I added clientConfigSVC in my factory where i want to use configuration function
angular.module('ds.coupons')
.factory('CouponsREST', ['Restangular', 'SiteConfigSvc','settings', 'clientConfigSvc',
function(Restangular, siteConfig, settings, clientConfig) { }
and then inside CouponsREST factory with function clientConfig.getConfig() i am getting value

Getting `state not defined` error when it is defined

In my angular application I want to go to another page on a click of a button. For that I use GoNext function. Below is my code that gives me state is not defined error. Can anyone tell me what is going on?
(function () {
angular.module("MyApp").controller("MainCtrl", ["$scope", "$state", "$http", MainCtrlFunction]);
function MainCtrlFunction($scope, $state, $http) {
....
$scope.GoNext = function () {
state.go("screen2");
}
}
})();
I do have a corresponding entry in my config file.
You've miss typed the service $state's name. It's just a confusion because you have two things named state on your code: the argument $state which is a service and the state of your aplication router; Anyways, it should look like:
$state.go("screen2");
Instead of:
state.go("screen2");
Need to use $state and make sure it's injected into your controller. Seems you used state w no dollar symbol.

Can't set angular $scope variable from a callback function in Ionic

I am new in angular js. I am working with web Sql in a test project for learning purpose. My insert operation is working fine. My problem is when i fetch all the records then i can't store it in $scope.todos=results.rows
My code is
tx.transaction(sql,[],myCallback)
function myCallback(tx,results)
{
console.log(results.rows); // shows objects in console
$scope.todos=results.rows;
}
In view the todos is not working with ng-repeat.
It might help to show all of your controller, or service. If it's a controller make sure you included the $scope parameter for example:
.controller('MyController', function ($scope){
}))
If you are doing this inside a service, save it in a variable inside the service, then from a controller where the "$scope" is available include your service then call your variable containing the results. This will also be helpful if you need to share those results with other controllers at a later time.
.service('MyDataService',function(){
var todos;
return {
.... set and get functions to access variable ...
getTodos: function() {
return todos;
}
};
});
And in controller
.controller('MyController', function ($scope, MyDataService){
$scope.todos = MyDataService.getTodos()
}))
There are also ways to get the $scope working in a service but I don't think it's a great idea.

AngularJS project structure and defintions

In app.js file I defined the following:
var app = angular.module("app", ["ngRoute"]);
In testController.js I defined the following:
app.controller('testController', ['$scope'], function($scope) {
$scope.temp1 = "";
$scope.temp2 = -1;
});
In testService.js I defined the following:
app.factory('testService', function ($http, $scope) {
'use strict';
return {
list: function (callback) {
$http.get('url?param=' + $scope.temp1).success(callback);
}
};
});
In testController.js and testService.js lint tells me that app is undefined. How can I tell both of the files that app is the app from app.js?
How can I tell testService.js that $scope.temp1 is actually taken from testController.js?
Thanks
First, all of your code should be wrapped in an immediately invoked function expression.
https://github.com/johnpapa/angular-styleguide#iife
(function(){
real code goes here
})();
This keeps the global variable space clean
To access app from the other code, you don't.. you retrieve it again. So your controller would look like this:
(function(){
angular.module("app").controller("testController", ....
})();
And finally, the controller part of your code has misplaced brackets. The closing ] should be after the function.
(function(){
angular.module("app").controller("testController", ['$scope',function($scope){
// function code here
}]
})();
And your service is a singleton (there is only one for the whole app. So, you would not pass scope to the constructor as you have, but you would pass it to the function that needed access to it.
But passing scope down to a service like that will probably tightly couple your controller to your service which is something you shouldn't be doing. You should be retrieving from the service and passing specific elements in that it needs rather than the scope that could change.

Restangular has no method one. AngularJs inejctions

Im having problem with injections.
app.js
angular.module('Help', []);
var app = angular.module('app', [
'restangular'
,'Help'
]);
app.$inject = ['RestangularProvider'];
app.config(
function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://localhost:8080/api');
}
)
help.js
function HelpCtrl($rootScope, $scope, Restangular){
Restangular.one('questions').getList();
}
HelpCtrl.$inject = ['$scope', '$rootScope','Restangular']; //"TAG1"
angular.module('Help').controller("HelpCtrl", HelpCtrl);
I get the following error:
Uncaught TypeError: Object [object Object] has no method 'one'
If I remove line TAG1, everything works. However I need to inject it the right way. What is the problem here?
The injector is used to help AngularJS know the order of parameters given to the function in case the variable name change (e.g. after minimizing your JavaScript).
In your case, you've switched up the order of your injector parameters and the method signature, meaning that AngularJS will think that $scope is $rootScope and vice versa.
Either remove your $inject or make sure the parameters are in the same order in both your method signature and in your injection array.

Resources