I am currently using Angular 1.5. I am using ui-router as my primary navigation mechanism. I am leveraging Angular components.
I understand that I can use .resolve on my states to instantiate services which are then passed down through my component hierarchy (mostly using one-way bindings).
One of my components is called literatureList and is used in more than one route/state. The literatureList component makes use of a specific service called literatureListService. literatureListService is only used by literatureList. literatureListService takes a while to instantiate, and uses promises etc.
In each of the .state definitions then I need to have a .resolve that instantiates literatureListService. This means that I need to refer to this literatureListService in each of the .state.resolve objects. This doesn't seem very DRY to me.
What I'd really like to do is remove the literatureListService references from the .state.resolve objects and 'resolve' the service from 'within' the literatureList component itself.
How do I code a 'resolve-style' mechanism within the literatureList component that will handle the async/promise nature of literatureListService? What is best practice for doing this?
Code snippets follow:
state snippets:
$stateProvider.state({
name: 'oxygen',
url: '/oxygen',
views: {
'spofroot': { template: '<oxygen booklist="$resolve.literatureListSvc"></oxygen>' }
},
resolve:{
literatureListSvc: function(literatureListService){
return literatureListService.getLiterature();
}
}
});
$stateProvider.state({
name: 'radium',
url: '/radium',
views: {
'spofroot': { template: '<radium booklist="$resolve.literatureListSvc"></radium>' }
},
resolve:{
literatureListSvc: function(literatureListService){
return literatureListService.getLiterature();
}
}
});
literatureListService:
angular.module('literature')
.factory('literatureListService',function($http,modelService){
// Remember that a factory returns an object, whereas a service is a constructor function that will be called with 'new'. See this for a discussion on the difference: http://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
console.log('literatureListService factory is instantiating - this will only happen once for each full-page refresh');
// This is a factory, and therefore needs to return an object containing all the properties that we want to make available
var returnObject = {}; // Because this is a factory we will need to return a fully-formed object (if it was a service we would simply set properties on 'this' because the 'context' for the function would already have been set to an empty object
console.log('service instantiation reporting that modelManager.isDataDirty='+modelService.isDataDirty);
// The getLiterature method returns a promise, and therefore can only be consumed via a promise-based mechanism
returnObject.getLiterature = function($stateParams){
console.log('literatureService.getLiterature will now return a promise (via a call to $http)');
return $http({method: 'GET', url: 'http://localhost:3000/literature/'});
};
return returnObject;
});
oxygen component html:
<div>
This is the OXYGEN component which will now render a literature list, passing in bookList.data as books
<literature-list books="$ctrl.booklist.data"></literature-list>
</div>
oxygen component js
angular.module('frameworks')
.component('oxygen',{
templateUrl:"frontend/framework/frameworks/oxygenComponent.html",
controller:function($http){
var $ctrl = this;
console.log('Hello from the oxygen component controller with literatureListSvc='+$ctrl.booklist); // Bound objects NOT YET AVAILABLE!!!!!!
this.$onInit = function() {
//REMEMBER!!!! - the bound objects being passed into this component/controller are NOT available until just before the $onInit event fires
console.log('Hello from the oxygen component controller onInit event with bookList='+JSON.stringify($ctrl.booklist));
};
}
,bindings:{ // remember to make these lowercase!!!
booklist:'<'
}
});
literatureList component html:
<div>
{{$ctrl.narrative}}
<literature-line ng-repeat="literatureItem in $ctrl.books" wizard="fifteen" book="literatureItem" on-tut="$ctrl.updateItemViaParent(itm)">555 Repeat info={{literatureItem.title}}</literature-line>
</div>
literatureList component js
angular.module('literature')
.component('literatureList',{
templateUrl:'frontend/literature/literatureListComponent.html',
//template:'<br/>Template here33 {{$ctrl.listLocalV}} wtfff',
// controller:function(literatureListService){
controller:function(){//literatureListService){
var $ctrl=this;
this.narrative = "Narrative will unfold here";
this.updateItemViaParent = function(book){
this.narrative = 'just got notified of change to book:'+JSON.stringify(book);
};
this.$onInit = function(){
console.log('literatureList controller $onInit firing with books='+JSON.stringify($ctrl.books));
};
this.$onChanges = function(){
console.log('literatureList controller $onChanges firing');
};
},
bindings: {
books:'<'
}
});
As JavaScript in reference based, you can crete object in your service and access it in all three controllers that you need.
For Example:
function serviceA() {
var vm = this;
vm.testObject = {};
vm.promise1().then(function(response) {
vm.testObject = response;
})
}
function ControllerA($scope, serviceA) {
$scope.testA = service.testObject;
}
In this case, as soon as the promise is resolved, all the controllers will get the value of the response and can be used in the partials respecively
Related
Hello here is my component :
angular.module('myApp').component('dendroCtrl', {
templateUrl: '/templates/dendro.html',
bindings: {
id: '=',
type: '=',
mini: "="
},
controller: function ($scope, Api) {
//Dendro
var test = mini;
I tried this :
var test = mini;
var test = this.mini;
var test = $scope.mini;
Mini is everytime undefined.
How could I use my bindings in my controller ? Thanks
EDIT
This is how I call the component :
<dendro-ctrl id="149" type="Demand" mini="false"></dendro-ctrl>
From the documentation:
Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that will be called at certain points in the life of the component. The following hook methods can be implemented:
$onInit() - Called on each controller after all the controllers on an element have been constructed and had their bindings initialized (and before the pre & post linking functions for the directives on this element). This is a good place to put initialization code for your controller.
$onChanges(changesObj) - Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound properties that have changed, and the values are an object of the form
So you can just use:
controller: function(Api) {
var ctrl = this;
ctrl.$onInit = function() {
console.log(ctrl.mini);
}
}
if you want to display the initial value of the mini binding.
I need to execute functions of some controllers when my application ends (e.g. when closing the navigator tab) so I've thought in a service to manage the list of those functions and call them when needed. These functions changes depending on the controllers I have opened.
Here's some code
Controller 1
angular.module('myApp').component('myComponent', {
controller: function ($scope) {
var mc = this;
mc.saveData = function(objectToSave){
...
};
}
});
Controller 2
angular.module('myApp').component('anotherComponent', {
controller: function ($scope) {
var ac = this;
ac.printData = function(objects, priority){
...
};
}
});
How to store those functions (saveData & printData) considering they have different parameters, so when I need it, I can call them (myComponent.saveData & anotherComponent.printData).
The above code is not general controller but the angular1.5+ component with its own controller scope. So the methods saveData and printData can only be accessed in respective component HTML template.
So to utilise the above method anywhere in application, they should be part of some service\factory and that needs to be injected wherever you may required.
You can create service like :
angular.module('FTWApp').service('someService', function() {
this.saveData = function (objectToSave) {
// saveData method code
};
this.printData = function (objects, priority) {
// printData method code
};
});
and inject it wherever you need, like in your component:
controller: function(someService) {
// define method parameter data
someService.saveData(objectToSave);
someService.printData (objects, priority);
}
I managed to make this, creating a service for managing the methods that will be fired.
angular.module('FTWApp').service('myService',function(){
var ac = this;
ac.addMethodForOnClose = addMethodForOnClose;
ac.arrMethods = [];
function addMethodForOnClose(idModule, method){
ac.arrMethods[idModule] = {
id: idModule,
method: method
}
};
function executeMethodsOnClose(){
for(object in ac.arrayMethods){
ac.arrMethods[object].method();
}
});
Then in the controllers, just add the method needed to that array:
myService.addMethodForOnClose(id, vm.methodToLaunchOnClose);
Afterwards, capture the $window.onunload and run myService.executeMethodsOnClose()
I'm new to Angular. I'm trying to use components (1.6). In the parent, I have an $http.get that gets data from a service and then assigns the response to a $scope variable. That scope variable is passed to a child component using one-way binding <. In the JavaScript, if I alert the variable passed in, I get "undefined", however, the html template in the child does show the variable. It's like there is a race condition happening and I don't know how to tell it to wait until the data from the service is loaded.
In my parent.js:
(function (angular) {
'use strict';
$http.get("http://localhost:52422/api/PayOffYourCc")
.then(function mySucces(response) {
$scope.baseline = response.data;
}
,
function myError(respone) {
$scope.baseline = response.statusText;
}
);
})(window.angular);
In my parent HTML template:
<thermometer baseline="baseline"></thermometer>
In my child component:
(function (angular) {
'use strict';
function drawChart(baselineVal) {
alert(baselineVal);
}
function ThermometerController($scope) {
var ctrl = this;
ctrl.$onInit = function () {
drawChart(ctrl.baseline);
};
}
angular.module('payOffYourCcApp').component('thermometer', {
templateUrl: '../PayOffYourCC/partials/thermometer.html',
transclude: true,
controller: ThermometerController,
bindings: {
baseline: '<'
}
});
})(window.angular);
In my child html template:
<div>
baseline:{{$ctrl.baseline}}
</div>
In the html, {{$ctrl.baseline}} is displayed fine, but when I alert it in the .js, it's undefined. Why is that? How can I make sure the {{$ctrl.baseline}} is in scope before the javascript loads?
Use the $onChanges life-cycle hook:
function ThermometerController($scope) {
var ctrl = this;
/* REPLACE THIS
ctrl.$onInit = function () {
drawChart(ctrl.baseline);
}; */
// WITH THIS
ctrl.$onChanges = function (changesObj) {
if (changesObj.baseline && changesObj.baseline.currentValue) {
drawChart(changesObj.baseline.currentValue);
};
};
}
The controller needs to wait for the data to come from the server. By using the $onChanges life-cycle hook, the drawChart function will be called when the data becomes available and will be called on subsequent updates.
For more information, see AngularJS Comprehensive Directive API Reference - Life-Cycle Hooks.
With Angular component, you should privilege communication from the child back to the parent since it allows a very cheap binding (&)
You can communicate from the parent to the child but it is more expensive (=).
I will give you an example on how to do it.
It is a not tested solution but you should have the idea.
You should change your parent to have a child api to transmit the data :
JS Parent :
(function (angular) {
'use strict';
$http.get("http://localhost:52422/api/PayOffYourCc")
.then(function mySucces(response) {
$scope.baseline = response.data;
$ctrl.apiChild.transmit(response.data);
}
,
function myError(respone) {
$scope.baseline = response.statusText;
}
);
})(window.angular);
HTML Parent :
<thermometer api="$ctrl.apiChild"></thermometer>
Change your child to have a function to receive the data from the parent and also change the binding to "=" :
JS Child :
(function (angular) {
'use strict';
function drawChart(baselineVal) {
alert(baselineVal);
}
function ThermometerController($scope) {
var ctrl = this;
ctrl.$onInit = function () {
drawChart(ctrl.baseline);
ctrl.api = {};
ctrl.api.transmit = ctrl.transmitData;
};
this.transmitData = function transmitData(data){
// here you get the data from the parent to the child
}
}
angular.module('payOffYourCcApp').component('thermometer', {
templateUrl: '../PayOffYourCC/partials/thermometer.html',
transclude: true,
controller: ThermometerController,
bindings: {
api : '='
}
});
})(window.angular);
This is the result of the fact that $http requests are asynchronous. The alert that happens when the child component initializes prints undefined, because at that instance the $http request that is retrieving the data has not returned yet. Since you're using > binding however, the template in your child component will update with the correct value as soon as the request resolves (which is pretty darn fast), so you don't ever see undefined actually printed in the template. In fact, I don't think angular will print undefined, I think it's just blank. So to your eye, it looks like it has the right value right away, when, in reality, it was momentarily undefined while the $http request was resolving.
I'm trying to follow John Papa's Controller Activation Process where the data that a controller needs is loaded at the constructor of the controller. However, my page is triggering a lot of errors due to Angular trying to bind to a null object until the data is loaded.
Example
Controller initializes and performs an AJAX call to fetch information about a movie. Meanwhile, the HTML tries to load information about the movie's director.
Controller.js
class MovieController {
constructor(movieHttp) {
this.movieHttp = movieHttp;
this.movie = null;
activate();
}
activate() {
this.movieHttp.getMovie(...).then(movieData => { this.movie = movieData; });
}
}
index.html
...
<span ng-bind="vm.movie.actor.name"></span>
...
Is there a nice way of resolving this issue other than changing the ng-bind into a function call, and then doing an if (!this.movie) { return; }?
You can set an empty movie object on your ctrl (or better yet a service), and update it when the ajax calls returns:
class MovieController {
constructor(movieHttp) {
this.movieHttp = movieHttp;
this.movieData = {
movie: {
actor: {
name: ''
},
title: ''
}
};
activate();
}
activate() {
this.movieHttp.getMovie(...).then(movieData => { this.movieData.movie = movieData;})
}
}
and your html:
<span ng-bind="vm.movieData.movie.actor.name"></span>
it could be annoying if the object is very complex however you set it only once and than you can easily figure out what's the retured object structure is (again a better place to store it would be a service).
another solution is using the router resolve property which forces the promise to be reolved before the controller is instantiated (and injecting the resolved object as a parameter to your controller)
ui-router has a convinent way for that (https://github.com/angular-ui/ui-router/wiki), but angular's default router also has this option (https://docs.angularjs.org/api/ngRoute/provider/$routeProvider)
I'm trying to figure out the "preferred" or "angular-way" of sharing properties or state between controllers/directives. There are several methods to implement this, but I want to keep with best-practice. Below are some banal examples of how this can be implemented:
1. Using $scope.$watch
// The parent controller/scope
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
$scope.state = {
myProperty: 'someState'; // Default value to be changed by some DOM element
};
}]);
// The child controller/scope.
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$watch('state.myProperty', function (newVal) {
// Do some action here on state change
});
}]);
Edit: Based on answers below, this is bad practice and should be avoided. It is untestable and places an unwanted DOM dependancy.
2. Using $broadcast
// The parent controller
angular.module('myModule').controller('parentController', ['$scope', function($scope) {
var myProperty = 'someState';
$scope.setState = function (state) {
myProperty = state; // Set by some other controller action or DOM interaction.
$scope.$broadcast('stateChanged', state); // Communicate changes to child controller
}
}]);
// The child controller.
angular.module('myModule').controller('childController', ['$scope', function($scope) {
$scope.$on('stateChanged', function (evt, state) {
// Do some action here
}
}]);
Edit: Equally bad practice as you need to know the placement of the controllers in the DOM in order to determine weather to use $broadcast (down the DOM) or $emit (up the DOM).
3. Using service
angular.module('myModule').factory('stateContainer', [function () {
var state = {
myProperty: 'defaultState'
},
listeners = [];
return {
setState: function (newState) {
state.myProperty = newState;
angular.forEach(listeners, function (listener) {
listener(newState);
});
},
addListener: function (listener) {
listeners.push(listener);
}
}
}]);
// The parent controller
angular.module('myModule').controller('parentController', ['$scope', 'stateContainer', function($scope, stateContainer) {
$scope.setState = function (state) {
stateContainer.setState(state);
};
}]);
// The child controller.
angular.module('myModule').controller('childController', ['$scope', 'stateContainer', function($scope, stateContainer) {
stateContainer.addListener(function (newState) {
// Do some action here
});
}]);
There are probably some approaches I've missed here, but you get the idea. I'm trying to find the best approach. Although verbose, I personally lean towards #3 in the list here. But I come from a Java and jQuery background where listeners are widely used.
Edit: Answers below are insightful. One talks of sharing state between parent/child directives using the require directive configuration. The other talks of sharing service or service properties directly to the scope. I believe that depending on the need, they are both right in what is or is not best practice in Angular.
Any of these will work if done correctly, but a variant on service is the preferred way AFAIK.
The question is, do you even need a listener in the service case? Angular itself will update any views (which is the purpose of the controller), so why do you need a listener or watch? It is sufficient to change the value itself for the view to be changed.
app.factory('stateService',function() {
return {
myState: "foo"
}
})
.controller('one',function($scope,stateService) {
$scope.changeState = function() {
stateService.myState = $scope.state;
};
})
.controller('two',function($scope,stateService) {
$scope.svc = stateService;
})
You can then do the following in your view (incomplete):
<div ng-controller="one">
<input name="state" ng-model="state"></input>
<button type="submit" ng-click="changeState()">Submit</button>
</div>
<div ng-controller="two">{{svc.myState}}</div>
Truth is, you don't even need to go that far with having a button and a function. If you just tie the ng-model together it will work:
<div ng-controller="one">
<input name="state" ng-model="svc.myState"></input>
</div>
<div ng-controller="two">{{svc.myState}}</div>
Try the following jsfiddle http://jsfiddle.net/cwt9L6vn/1/
There is no such thing as parent and child controllers in AngularJS. There are only parent and child directives, but not controllers. A directive can have a controller that it exposes as an API to other directives.
Controllers are not related to the DOM hierarchy so they can't have children. They also don't create their own scope. So you never know if you have to $broadcast or $emit to talk to other controllers.
If you start using $broadcast from a controller, then you're going to get stuck not knowing if the other controller is up or down. That's when people start doing stuff like $rootScope.$broadcast(..) which is a very bad practice.
What you are looking for are directives that require other directives.
var app = angular.modeul('myApp',[]);
// use a directive to define a parent controller
app.directive('parentDir',function() {
return {
controller: function($scope) {
this.myFoo = function() {
alert("Hello World");
}
}
});
// use a directive to enforce parent-child relationship
app.directive('childDir',function() {
return {
require: '^parentDir',
link: function($scope, $el, $attr, parentCtrl) {
// call the parent controller
parentCtrl.myFoo();
}
});
Using the require feature of a directive does two important things.
Angular will enforce the relationship if it's not optional.
The parent controller is injected into the child link function.
There is no need to $broadcast or $emit.
Another option that is also effective is to use directives to expose an API.
// this directive uses an API
app.directive('myDir',function() {
return {
scope: {
'foo': '&'
},
link: function($scope, $el, $attr) {
// when needed, call the API
$scope.foo();
}
});
// in the template
<div ng-controller="parentController">
<div my-dir foo="parentController.callMyMethod();"></div>
</div>