Call function from another Controller Angular Js - javascript

I am new to using angular js and i have declare many controller and now i want to user function of one controller into another controller. here is my sample code.
app.controller('Controller1',function($scope,$http,$compile){
$scope.test1=function($scope)
{
alert("test1");
}
});
app.controller('Controller2',function($scope,$http,$compile){
$scope.test2=function($scope)
{
alert("test1");
}
});
app.controller('Controller3',function($scope,$http,$compile){
///
});
Now i want to call test2 function inside controller3.
Can anybody help..
Thanks in Avance... :)

You can't call a method from a controller within a controller. You will need to extract the method out, create a service and call it. This will also decouple the code from each other and make it more testable
(function() {
angular.module('app', [])
.service('svc', function() {
var svc = {};
svc.method = function() {
alert(1);
}
return svc;
})
.controller('ctrl', [
'$scope', 'svc', function($scope, svc) {
svc.method();
}
]);
})();
Example: http://plnkr.co/edit/FQnthYpxgxAiIJYa69hu?p=preview

Best way is write a service and use that service in both controllers. see the documentation Service documentation
If you really want to access controller method from another controller then follow the below option:
emitting an event on scope:
function FirstController($scope) { $scope.$on('someEvent', function(event, args) {});}
function SecondController($scope) { $scope.$emit('someEvent', args);}

The controller is a constructor, it will create a new instance if for example used in a directive.
You can still do what you wanted, assuming that your controllers are in the same scope, just do:
Note they must be in the same scope, could still work if a child scope was not isolated.
The directive's definition:
{
controller: Controller1,
controllerAs: 'ctrl1',
link: function($scope) {
$scope.ctrl1.test1(); // call a method from controller 1
$scope.ctrl2.test2(); // created by the directive after this definition
$scope.ctrl3.test3(); // created by the directive after this definition
}
}
....
{
controller: Controller2,
controllerAs: 'ctrl2',
link: function($scope) {
$scope.ctrl1.test1(); // created earlier
$scope.ctrl2.test2(); // ...
$scope.ctrl3.test3(); // created by the directive after this definition
}
}
....
{
controller: Controller3,
controllerAs: 'ctrl3',
link: function($scope) {
$scope.ctrl1.test1();
$scope.ctrl2.test2();
$scope.ctrl3.test3();
}
}
This should work.

Related

AngularJS Directive binding to controller

I'm trying to figure out AngularJS directives. I've got the following JSFiddle with an example of something I'm trying to do. https://jsfiddle.net/7smor9o4/
As you can see in the example, I expect the vm.alsoId variable to be equal to vm.theId. In the template vm.theId displays the correct value but vm.alsoId does not.
What am I doing wrong? How could I accomplish my goal.
If it helps the final idea is to execute something as the following:
function directive(service) {
var vm = this;
vm.entity = null;
init();
function init() {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
}
}
As you've noticed, the bindToController bindings are not immediately available in the controller's constructor function (unlike $scope, which are). What you're looking for is a feature introduced with Angular 1.5: Lifecycle Hooks, and specifically $onInit.
You had the right idea; simply replace your init function definition and invocation as follows:
vm.$onInit = function () {
service.getEntity(vm.theId).then(function (entity) {
vm.entity = entity;
});
};
And here is your updated fiddle.
(Alternatively, without this solution, you'd have needed a watch.)
Angular recommends that you bind a controller "only when you want to expose an API to other directives. Otherwise use link."
Here's a working fiddle using the link function.
angular.module('app', [])
.directive('directive', directive);
angular.element(function() {
angular.bootstrap(document, ['app']);
});
function directive() {
return {
restrict: 'E',
scope: {
theId: '<'
},
template: `
alsoId: <span ng-bind="alsoId"></span>
theId: <span ng-bind="theId"></span>`,
link: link
};
}
function link(scope, element, attrs) {
init();
function init() {
scope.alsoId = scope.theId;
}
}

How can I run function in two separated controllers in angularjs

I have two separate angularjs controllers
that are named HomeController and SearchController.
I have a function that named Search() in HomeController.
How can I run search function from searchController?
define the 'search' function in a factory, inject that factory into both controllers then you can access 'search' function from both controllers.
sample:
app.controller('HomeController', function(searchFactory){
//calling factory function
//searchFactory.search();
});
app.controller('searchController ', function(searchFactory){
//calling factory function
//searchFactory.search();
});
app.factory('searchFacotry', function(){
return{
search: function(arg){
alert('hello world');
};
};
});
I have made this Plunker which does the above. The app.js file looks like this. It uses a factory declaration. Alternatively if you just want this function to store and return some data then you can use $rootScope service of angular, it is accessible globally. Services are prefered when they are performing some operation. Take a look at this Link which have answers explaining the use of services vs rootScope.
app.controller('HomeCtrl', function($scope, searchService) {
$scope.ctrl1Fun= function() {
searchService.search();
}
});
app.controller('SearchCtrl', function($scope, searchService) {
$scope.ctrl2Fun= function() {
searchService.search();
}
})
app.factory('searchService', function(){
function search(){
alert('hello World')
}
var service = {search : search}
return service
});

How to setup $emit in directive in my case

I am trying to use $emit in my code for a directive.
I have
(function () {
angular
.module('myApp')
.directive('testDirective', testDirective);
function testDirective() {
var directive = {
link: link,
restrict: 'A',
controller: testCtrl,
controllerAs: 'vm'
};
return directive;
function link(scope, element, attrs) {
}
}
function testCtrl() {
var vm = this;
// do something
vm.$emit('someEvent', {'id': '123'})
}
})();
However, I am getting 'TypeError: vm.$emit is not a function'. I am not sure how to fix this. Can anyone help? Thanks a lot!
controllerAs just means that scoped variables are attached directly to the controller -- it doesn't mean that the controller is an instance of an angular scope itself. In this case, you'll need to inject the scope into the controller and then emit the event from on the scope:
function testCtrl($scope) {
// do something
$scope.$emit('someEvent', {'id': '123'})
}
Also beware, the normal injection rules apply -- If you're going to minify this, you'll probably need something like:
testCtrl['$inject'] = ['$scope'];

AngularJS: Controller split across two files? [duplicate]

I have three controllers that are quite similar. I want to have a controller which these three extend and share its functions.
Perhaps you don't extend a controller but it is possible to extend a controller or make a single controller a mixin of multiple controllers.
module.controller('CtrlImplAdvanced', ['$scope', '$controller', function ($scope, $controller) {
// Initialize the super class and extend it.
angular.extend(this, $controller('CtrlImpl', {$scope: $scope}));
… Additional extensions to create a mixin.
}]);
When the parent controller is created the logic contained within it is also executed.
See $controller() for for more information about but only the $scope value needs to be passed. All other values will be injected normally.
#mwarren, your concern is taken care of auto-magically by Angular dependency injection. All you need is to inject $scope, although you could override the other injected values if desired.
Take the following example:
(function(angular) {
var module = angular.module('stackoverflow.example',[]);
module.controller('simpleController', function($scope, $document) {
this.getOrigin = function() {
return $document[0].location.origin;
};
});
module.controller('complexController', function($scope, $controller) {
angular.extend(this, $controller('simpleController', {$scope: $scope}));
});
})(angular);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script>
<div ng-app="stackoverflow.example">
<div ng-controller="complexController as C">
<span><b>Origin from Controller:</b> {{C.getOrigin()}}</span>
</div>
</div>
Although $document is not passed into 'simpleController' when it is created by 'complexController' $document is injected for us.
For inheritance you can use standard JavaScript inheritance patterns.
Here is a demo which uses $injector
function Parent($scope) {
$scope.name = 'Human';
$scope.clickParent = function() {
$scope.name = 'Clicked from base controller';
}
}
function Child($scope, $injector) {
$injector.invoke(Parent, this, {$scope: $scope});
$scope.name = 'Human Child';
$scope.clickChild = function(){
$scope.clickParent();
}
}
Child.prototype = Object.create(Parent.prototype);
In case you use the controllerAs syntax (which I highly recommend), it is even easier to use the classical inheritance pattern:
function BaseCtrl() {
this.name = 'foobar';
}
BaseCtrl.prototype.parentMethod = function () {
//body
};
function ChildCtrl() {
BaseCtrl.call(this);
this.name = 'baz';
}
ChildCtrl.prototype = Object.create(BaseCtrl.prototype);
ChildCtrl.prototype.childMethod = function () {
this.parentMethod();
//body
};
app.controller('BaseCtrl', BaseCtrl);
app.controller('ChildCtrl', ChildCtrl);
Another way could be to create just "abstract" constructor function which will be your base controller:
function BaseController() {
this.click = function () {
//some actions here
};
}
module.controller('ChildCtrl', ['$scope', function ($scope) {
BaseController.call($scope);
$scope.anotherClick = function () {
//other actions
};
}]);
Blog post on this topic
Well, I'm not exactly sure what you want to achieve, but usually Services are the way to go.
You can also use the Scope inheritance characteristics of Angular to share code between controllers:
<body ng-controller="ParentCtrl">
<div ng-controller="FirstChildCtrl"></div>
<div ng-controller="SecondChildCtrl"></div>
</body>
function ParentCtrl($scope) {
$scope.fx = function() {
alert("Hello World");
});
}
function FirstChildCtrl($scope) {
// $scope.fx() is available here
}
function SecondChildCtrl($scope) {
// $scope.fx() is available here
}
You don't extend controllers. If they perform the same basic functions then those functions need to be moved to a service. That service can be injected into your controllers.
Yet another good solution taken from this article:
// base controller containing common functions for add/edit controllers
module.controller('Diary.BaseAddEditController', function ($scope, SomeService) {
$scope.diaryEntry = {};
$scope.saveDiaryEntry = function () {
SomeService.SaveDiaryEntry($scope.diaryEntry);
};
// add any other shared functionality here.
}])
module.controller('Diary.AddDiaryController', function ($scope, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
}])
module.controller('Diary.EditDiaryController', function ($scope, $routeParams, DiaryService, $controller) {
// instantiate base controller
$controller('Diary.BaseAddEditController', { $scope: $scope });
DiaryService.GetDiaryEntry($routeParams.id).success(function (data) {
$scope.diaryEntry = data;
});
}]);
You can create a service and inherit its behaviour in any controller just by injecting it.
app.service("reusableCode", function() {
var reusableCode = {};
reusableCode.commonMethod = function() {
alert('Hello, World!');
};
return reusableCode;
});
Then in your controller that you want to extend from the above reusableCode service:
app.controller('MainCtrl', function($scope, reusableCode) {
angular.extend($scope, reusableCode);
// now you can access all the properties of reusableCode in this $scope
$scope.commonMethod()
});
DEMO PLUNKER: http://plnkr.co/edit/EQtj6I0X08xprE8D0n5b?p=preview
You can try something like this (have not tested):
function baseController(callback){
return function($scope){
$scope.baseMethod = function(){
console.log('base method');
}
callback.apply(this, arguments);
}
}
app.controller('childController', baseController(function(){
}));
You can extend with a services, factories or providers. they are the same but with different degree of flexibility.
here an example using factory : http://jsfiddle.net/aaaflyvw/6KVtj/2/
angular.module('myApp',[])
.factory('myFactory', function() {
var myFactory = {
save: function () {
// saving ...
},
store: function () {
// storing ...
}
};
return myFactory;
})
.controller('myController', function($scope, myFactory) {
$scope.myFactory = myFactory;
myFactory.save(); // here you can use the save function
});
And here you can use the store function also:
<div ng-controller="myController">
<input ng-blur="myFactory.store()" />
</div>
You can directly use $controller('ParentController', {$scope:$scope})
Example
module.controller('Parent', ['$scope', function ($scope) {
//code
}])
module.controller('CtrlImplAdvanced', ['$scope', '$controller', function ($scope, $controller) {
//extend parent controller
$controller('CtrlImpl', {$scope: $scope});
}]);
You can use Angular "as" syntax combined with plain JavaScript inheritance
See more details here
http://blogs.microsoft.co.il/oric/2015/01/01/base-controller-angularjs/
I wrote a function to do this:
function extendController(baseController, extension) {
return [
'$scope', '$injector',
function($scope, $injector) {
$injector.invoke(baseController, this, { $scope: $scope });
$injector.invoke(extension, this, { $scope: $scope });
}
]
}
You can use it like this:
function() {
var BaseController = [
'$scope', '$http', // etc.
function($scope, $http, // etc.
$scope.myFunction = function() {
//
}
// etc.
}
];
app.controller('myController',
extendController(BaseController,
['$scope', '$filter', // etc.
function($scope, $filter /* etc. */)
$scope.myOtherFunction = function() {
//
}
// etc.
}]
)
);
}();
Pros:
You don't have to register the base controller.
None of the controllers need to know about the $controller or $injector services.
It works well with angular's array injection syntax - which is essential if your javascript is going to be minified.
You can easily add extra injectable services to the base controller, without also having to remember to add them to, and pass them through from, all of your child controllers.
Cons:
The base controller has to be defined as a variable, which risks polluting the global scope. I've avoided this in my usage example by wrapping everything in an anonymous self-executing function, but this does mean that all of the child controllers have to be declared in the same file.
This pattern works well for controllers which are instantiated directly from your html, but isn't so good for controllers that you create from your code via the $controller() service, because it's dependence on the injector prevents you from directly injecting extra, non-service parameters from your calling code.
I consider extending controllers as bad-practice. Rather put your shared logic into a service. Extended objects in javascript tend to get rather complex. If you want to use inheritance, I would recommend typescript. Still, thin controllers are better way to go in my point of view.

Call an expression from the isolated scope with & not working directly

I'm quite new to Angular, so I'm pretty sure there's something I'm missing here.
I just read an article about isolated scopes, with expressions in particular using & symbol.
This is the article, which includes a fiddle.
I'm trying to do something more simple, I want to use also a function but don´t want to use a button to do the calling, I'd like to directly call the function. I reduced the code in the fiddle to something similar to what I want but it has no effect, the function is not being called, or it is but is not doing what I expect.
If I uncomment line #12 I 'Hello' is displayed, and if comment then I expected 'as' to be displayed in the textbox, but instead it's cleared. What am I missing here?
Thanks,
PS. I can´t seem to make the snipped work, but the fiddle works fine.
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict: 'E',
scope: {
isolatedExpressionFoo: '&'
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
//$scope.isolatedExpressionFoo();
$scope.updateFoo = function () {
$scope.foo = 'as';
}
}]);
<div ng-controller="MyCtrl">
<input ng-model="foo">
<my-component isolated-expression-foo="updateFoo()" />
</div>
The $scope from the controller and the directive are two different ones. The controller $scope has no access to the isolatedExpressionFoo function.
To instantly call the function provided to your directive (from within the directive) you will need to implement a controller for said directive.
E.g.
var myModule = angular.module('myModule', [])
.directive('myComponent', function () {
return {
restrict:'E',
scope:{
isolatedExpressionFoo:'&'
},
controller: function($scope){
$scope.isolatedExpressionFoo();
}
};
})
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.foo = 'Hello!';
$scope.updateFoo = function () {
$scope.foo = 'as';
}
}]);

Categories