angularjs 1.5 component dependency injection - angularjs

this may sound newb, but I have been following this tutorial for angularjs component.
I am new to components and how do I inject a constant Utils or authService to my component like this?
app.component('tlOverallHeader', {
bindings: {
data: '='
},
templateUrl: 'js/indexTimeline/components/tl_overallHeader/templates/tl_overallHeader.html',
controller: function() {
this.ms = 'tlOverallheader!'
}
})
thanks!

You can inject services to component controller like this:
angular.module('app.module')
.component('test', {
templateUrl: 'views/someview.html',
bindings: {
subject: '='
},
controller: ['$scope', 'AppConfig', TestController]
});
function TestController(scope, config) {
scope.something = 'abc';
}
or like this:
angular.module('app.module')
.component('test', {
templateUrl: 'views/someview.html',
bindings: {
subject: '='
},
controller: TestController
});
TestController.$inject = ['$scope', 'AppConfig']
function TestController(scope, config) {
scope.something = 'abc';
}

You should be able to inject services into your component's controller just like a standalone controller:
controller: function(Utils, authService) {
this.ms = 'tlOverallheader!'
authService.doAuthRelatedActivities().then(...);
}

The accepted answer isn't minification safe. You can use the minification-safe dependency injection notation here too:
controller: ['Utils', 'authService',
function(Utils, authService) {
this.ms = 'tlOverallheader!'
authService.doAuthRelatedActivities().then(...);
},
]

For Functional style programming which utilizes Factory style services the following syntax gets the job done:
angular.module('myApp')
.component('myComponent', {
templateUrl: 'myTemplate.html',
controller: ['myFactory', function(myFactory){
var thisComponent = this;
thisComponent.myTemplatemsg = myFactory.myFunc();
}]
})
.factory('myFactory', [ function(){
return {
myFunc: function(){
return "This message is from the factory";
}
};
}]);
A word of caution: The same component service/factory you setup for your component is also injectable (and thus accessible) anywhere else in your app including the parent scope and other component scopes. This is powerful but can be easily abused. Hence, it is recommended components only modify data within their own scope so there's no confusion on who is modifying what. For more on this see https://docs.angularjs.org/guide/component#component-based-application-architecture .
However, even the discussion in the aforementioned link only addresses the
cautionary use of the two-way-binding property value of '='when using the bindings object. Therefore the same reasoning should apply for component services and factories. If you plan on using the same service or factory in other component scopes and/or the parent scope I recommend setting up your service/factory where your parent scope resides or where your intended congregation of services/factories reside. Especially if you have numerous components using the same service/factory. You don't want it located in some arbitrary component module of which would be hard to find.

Related

angularJS controller property injection

Is is possible to use property injection in angularJS?
Scenario
I know this will work
app
.module('myapp')
.config(function($stateProvider) {
$stateProvider.state('the-state', {
url: '/the/url',
templateUrl: 'view.html',
controller: 'ctrl',
controllerAs: 'vm',
resolve: {
'boolFlag': function(service){return service.getBoolean();}
}
});
})
.service('service', function(){
this.getBoolean = function() {return ...};
})
.controller('ctrl', function(boolFlag) {
this.boolFlag = boolFlag;
this.execute = function(){...};
});
<div ng-show="vm.boolFalg">
simple dynamic content
</div>
<button type="button" ng-click="vm.execute()">Click Me</button>
But it feels leaky. boolFlag` is only used in the view to show/hide content. Is there I way I can resolve the controller and set the boolFlag property on the controller instance? I assume providers or factories would be the way to go, but I'm going around in circles trying to make sense of it.
I envision it would look something like
app
.module('myapp')
.config(function($stateProvider) {
$stateProvider.state('the-state', {
url: '/the/url',
templateUrl: 'view.html',
controller: 'ctrl',
controllerAs: 'vm',
});
})
.provider('ctrlProvider', function(ctrlProvider, service) {
var ctrl = ctrlProvider.$get/invoke/build/create();
ctrl.boolFlag = service.getBoolean();
return ctrl;
})
.service('service', function(){
this.getBoolean = function() {return ...};
})
.controller('ctrl', function() {
this.execute = function(){...};
});
I could also be going about this the wrong way. Many controllers will need the boolFlag property. Maybe it should be part of a $parentScope? But I don't know how to code that.
Update
I was thinking about this more last night. The boolFlag doesn't need to be associated to the controller at all. It only needs to be part of the scope. $scope.boolFlag = service.getBoolean();
The question then becomes, how can I populate $scope without the controller?
you could use factory to maintain the value of boolFlag so that it is shared between the controllers. It is better to avoid using $parentScope. This explains how to proceed with that. If you need to set the value of factory initially you could also use it in app.config of your main module to set its value.

How to test a $uibModal instance controller?

I'm trying to test a certain controller functionality with Jasmine unit testing.
I have a function which opens a modal instance with a new controller:
function openFilterModal(data) {
var modalInstance = $uibModal.open({
controller: FilterModalController,
controllerAs: 'vm',
templateUrl: 'modal.html',
resolve: {
data: function () {
return data;
}
}
});
return modalInstance.result;
}
The controller is defined below:
FilterModalController.$inject = ['alertsModalService', '$uibModalInstance', 'data', '$scope', 'logger', '$timeout'];
function FilterModalController(alertsModalService, $uibModalInstance, data, $scope, logger, $timeout) {
// code goes here }
When I try to call 'openFilterModal', I'm unable to get the controller instance, just getting the promise from it.
I've tried to used the $controller(FilterModalController) function in Jasmine, but it couldn't find the controller.
What is the best practice in that case?
Should I add the controller definition to my module? right now it defined like anonymous controller... not sure if that's good behavior or not.
like that:
app.controller('FilterModalController', FilterModalController);
Is it ok to define 2 controllers on the same module?
Or there is another way to get test the controller?
Thanks!

Calling a controller inside a factory method

Currently I have a factory method like this:
open_model: function(som_id){
var modelSettings = $aside({
controller: // a very big controller code
size: 'sm',
placement: 'right',
templateUrl: 'views/id/modal.html',
resolve: {
modal_data: function(){
return area_id;
}
}
});
},
I want to separate out the controller from this method and call it by name. Currently this is >100 lines of code in controller section and hence it makes factory dirty. So is there a way to define the controller somewhere else, and call the controller by name instead of writing the code.
In addition to #nikjohn's answer, you can also create a separate angular controller and refer it within you modelSettings. Since you already said your controller code for the modal exceeds 100 lines, this even might be a better solution.
angular.module('myApp').controller('ModalInstanceCtrl', ['$scope', 'modal_data', function($scope, modal_data) {
// modal controller code goes here
}]);
// and refer it in your factory method
open_model: function(som_id){
var modelSettings = $aside({
controller: 'ModalInstanceCtrl'
size: 'sm',
placement: 'right',
templateUrl: 'views/id/modal.html',
resolve: {
modal_data: function(){
return area_id;
}
}
});
}
You can define your controller wherever you want, and inject it as a dependency into your factory (although I don't know what a controller would be doing within a factory).
controllerFn: function(a, b) {
// ......
}
open_model: function(som_id, controllerFn){
var modelSettings = $aside({
controller: controllerFn,
size: 'sm',
placement: 'right',
templateUrl: 'views/id/modal.html',
resolve: {
modal_data: function(){
return area_id;
}
}
});
},
You should never access a controller within a factory. You're mixing concerns by doing that. If there's functionality you want to separate out, create another service and inject that service into your factory. Your controller should be leveraging services and factories, not the other way around.

Parametrise controller to work in different directives

I need to work with several different directives in angularJS. The directives have different templates and the controllers should work in very similar way, with very small changes each-other.
I was thinking to use just one shared controller that adapt its behaviour to the directive it's included like the idea described in code:
var module = angular.module('app', []);
module.directive('myFirstDirective', function () {
return {
scope: {},
controller: 'MyController',
templateUrl: './directives/first.html'
};
});
module.directive('mySecondDirective', function () {
return {
scope: {},
controller: 'MyController',
templateUrl: './directives/second.html'
};
});
module.controller('MyController', function ($scope) {
$scope.myEvent = function () {
//if it's first directive do this
//if it's second directive do that
};
});
Is there any way in angular to do this?
You can use ng-init="callback1()" and ng-init="callback2()" in your directives. And describe both callbacks in your controller.

Angular router with popup

I'm currently working on an app where a button triggers a method that will emit an event to elsewhere. This works great, however I also want to add a url to trigger this action.
So currently my button looks like this
<a class="addJob" ng-click="addNewJob()" ng-controller="AddJobController"></a>
But what I really want is it to just be
<a class="addJob" href="/new"></a>
Now, I can't figure out how to do the routing for this. It would mean that when I go to /new, the AddJobController should be triggered.
When I go directly to http://www.example.com/new, it should still load the page properly and trigger that action.
I don't want to create a separate page for this route as it is an essential part of the app flow.
(Think of it like when you create a new note in trello.com)
One Option
If you are willing to move to uiRouter, this is a common pattern.
Copied and pasted directly from the uiRouter FAQ
https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state
$stateProvider.state("items.add", {
url: "/add",
onEnter: ['$stateParams', '$state', '$modal', '$resource', function($stateParams, $state, $modal, $resource) {
$modal.open({
templateUrl: "items/add",
resolve: {
item: function() { new Item(123).get(); }
},
controller: ['$scope', 'item', function($scope, item) {
$scope.dismiss = function() {
$scope.$dismiss();
};
$scope.save = function() {
item.update().then(function() {
$scope.$close(true);
});
};
}]
}).result.then(function(result) {
if (result) {
return $state.transitionTo("items");
}
});
}]
})
Second Option
The second options would be to launch the modal the constructor of your controller. I have included a modalFactory. This is a common pattern. It allows your modals to be reusable, and cleans up your controllers. The uiRouter example above should use the factory pattern as well to abstract the modal setup out of the state config.
This example should work with ngRouter.
app.controller('addJobModalController', ['modalFactory', function(modalFactory) {
modalFactory.addJob();
}]);
app.factory('modalFactory', ['$modal', function($modal) {
return {
addJob: function() {
return $modal.open({
templateUrl: 'views/addjob-modal.html',
controller: 'AddJobController',
size: 'md'
});
}
}
}]);
The addJob() method returns the modal's promise. If you want, you can store this promise in the factory to be returned by another method so that another controller or service can act on the result of the modal.

Resources