I have an Angularjs directive 'ExampleDirective' which has the controller 'ExampleController'. The controller defines two Promise objects where each Promise object makes an Http GET request and returns the response.
In the directive, we get the response data from the promise objects and process them to render the directive.
ExampleDirective gets instantiated twice within the same view and each instance makes it's own Http GET requests. This causes performance issues on the front end due to two requests sent at the same time to make expensive database calls and read from the same table as well.
Controller:
angular.module('exampleModule')
.constant("EXAMPLE_URL", "{% url 'example:get_example' %}")
.controller('exampleCtrl', ['$scope', '$http', 'EXAMPLE_URL', exampleCtrl]);
function exampleCtrl($scope, $http, EXAMPLE_URL) {
$scope.examplePromise = $http.get(EXAMPLE_URL).then(function(response) {
return response.data;
});
}
Directive:
angular.module('exampleModule')
.directive('exampleDirective', ['exampleFactory', 'STATIC_URL', '$http', '$window', exampleDirective]);
function exampleDirective(exampleFactory, STATIC_URL, $http, $window) {
return {
scope: {
title:'#?',
loadingImage:'#?',
},
restrict: 'AE',
templateUrl: STATIC_URL + 'example/example-template.html',
controller: "exampleCtrl",
link: function (scope, element, attrs) {
//add default options:
if (!scope.title) {
scope.title = 'Example Title';
}
if (!scope.loadingImage) {
scope.loadingImage = '';
}
scope.examplePromise.then(function(data) {
scope.exampleData = data;
// do something
});
}
};
}
Is there a way to instantiate a directive multiple times but not have to make the Http GET requests in the controller twice?
UPDATE
This is what I did, I added a service as suggested in the answer.
Service:
angular.module('chRatingsModule')
.factory('chExampleFactory', ['$http', 'EXAMPLE_URL', chExampleFactory]);
function chExampleFactory($http, EXAMPLE_URL) {
var api = {}
var promise = null;
api.examplePromise = examplePromise;
function examplePromise() {
if (promise == null) {
promise = $http.get(EXAMPLE_URL).then(function(response) {
return response.data;
});
}
return promise;
}
return api;
}
Updated Directive:
angular.module('exampleModule')
.directive('exampleDirective', ['exampleFactory', 'STATIC_URL', '$http', '$window', exampleDirective]);
function exampleDirective(exampleFactory, STATIC_URL, $http, $window) {
return {
scope: {
title:'#?',
loadingImage:'#?',
},
restrict: 'AE',
templateUrl: STATIC_URL + 'example/example-template.html',
link: function (scope, element, attrs) {
exampleFactory.examplePromise.then(function(data) {
scope.exampleData = data;
// do something
});
}
};
}
First solution, probably the best one: don't make the call from the directive, which should just be a graphical element. Do the call from the controller, and pass the data as argument to both directives.
Second solution, use a service in the directive, and always return the same promise:
myModule.factory('myService', function($http) {
var promise = null;
var getData = function() {
if (promise == null) {
promise = $http.get(...).then(...);
}
return promise;
};
return {
getData: getData
};
});
The controller defines two Promise objects where each Promise object
makes an Http GET request and returns the response.
Change to:
The SERVICE defines two Promise objects where each Promise object
makes an Http GET request and returns the response.
The service then can remember that it has already done the GET(s) and just return their result every subsequent time it is asked for them.
Related
I have two controllers on same page. What I am trying to achieve is if specific value is 1 call controller 1 and if 0 then controller 2. But the problem is that I am getting value inside controllers which is not accessible outside the controller, so how can I achieve this?
This case calls for a service, which can be shared between controllers.
All you have to do is inject the service into both controllers and update the variable in the service.
angular.module('app').service('myService', function() {
var self = this;
self.isActive;
self.setActive = function(val) {
self.isActive = val;
};
self.getActive = function() {
return self.isActive;
})
. controller('first', function(myService) {
var isActive = myService.getActive();
})
. controller('second', function(myService) {
var isActive = myService.getActive();
})
Both controllers would have the same value, you would just have to handle managing them during the life cycle of your app via the controllers.
Note that you can do anything you want in a service in terms of logic, you just have to share the service with the required controllers. It would be more likely that a function would handle the logic which you are splitting into different controllers.
// Inside the service
self.handleActive = function(isActive) {
if (isActive) {
// Do something
} else {
// Do other
}
};
Use directive for this purpose
global.directive('dynamicCtrl', ['$compile', '$parse',function($compile,
$parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function(scope, elem) {
var name = $parse(elem.attr('dynamic-ctrl'))(scope);
elem.removeAttr('dynamic-ctrl');
// add your condition here
if(condition == true){
elem.attr('ng-controller',"first");
}
else{
elem.attr('ng-controller',"second");
}
$compile(elem)(scope);
}
};
}]);
use in html as
i've seen many posts about this subject, but not specificly about this question.
I'm wondering if there could be a generic directive/controller in AngularJs to disable a button (that calls an ajax request) and re-enable it after the request ends.
I've used the word "generic" because i've seen some solutions using a callback after a specific ajax request, but it's not what i need.
I need that:
when clicking on a button, and the button calls an ajax request, it becomes disabled until the request ends.
Thank you for your help
Here is a possibility.
You can think of http service calls just as a promise. Once a http service call is fulfilled then it will call the next promise in the chain, if there is one.
You can receive a funcion in a directive, then do a wrapping call to it and chain another function to it. So this way you know when the promise is being executed and when it's fulfilled.
You need to be sure to retun the promise in the controller. Then pass that funcion to the directive.
Check the following example
https://codepen.io/bbologna/pen/zdpxoB
JS
var app = angular.module('testApp', []);
app.factory('fakeHttpService', ['$timeout', function($timeout){
var doSomething = function(value) {
return new Promise(function(resolve, reject) {
$timeout(() => { resolve(value + 1); $timeout() }, 1000);
})
}
return { doSomething: doSomething }
}])
app.controller('sampleController', ['$scope', 'fakeHttpService',
function($scope, fakeHttpService) {
$scope.doSomething = function(value){
return fakeHttpService.doSomething(value);
}
}
])
app.directive('buttonAsync', function(){
return {
restrict: 'E',
template: `<button ng-click="excecute()" ng-disabled="disabled">DO</button>`,
scope: {
on : '&'
},
controller : ['$scope', function($scope) {
$scope.disabled = false;
$scope.excecute = function() {
$scope.disabled = true;
$scope.on()
.then(function() {
$scope.disabled = false;
})
}
}]
}
})
Html
<div ng-app="testApp" ng-controller="sampleController">
<button-async on="doSomething(3)"></button-async>
</div>
I'm with a problem with binding an object of a Factory and a Controller and it's view.
I am trying to get the fileUri of a picture selected by the user. So far so good. The problem is that I am saving the value that file to overlays.dataUrl. But I am referencing it on the view and it isn't updated. (I checked and the value is actually saved to the overlays.dataUrl variable.
Here goes the source code of settings.service.js:
(function () {
"use strict";
angular
.module("cameraApp.core")
.factory("settingsService", settingsService);
settingsService.$inject = ["$rootScope", "$cordovaFileTransfer", "$cordovaCamera"];
function settingsService($rootScope, $cordovaFileTransfer, $cordovaCamera) {
var overlays = {
dataUrl: "",
options: {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
}
};
var errorMessages = [];
var service = {
overlays: overlays,
selectOverlayFile: selectOverlayFile,
errorMessages: errorMessages
};
return service;
function selectOverlayFile() {
$cordovaCamera.getPicture(overlays.options).then(successOverlay, errorOverlay);
}
//Callback functions
function successOverlay(imageUrl) {
//If user has successfully selected a file
var extension = "jpg";
var filename = getCurrentDateFileName();
$cordovaFileTransfer.download(imageUrl, cordova.file.dataDirectory + filename + '.' + extension, {}, true)
.then(function (fileEntry) {
overlays.dataUrl = fileEntry.nativeURL;
}, function (e) {
errorMessages.push(e);
});
}
function errorOverlay(message) {
//If user couldn't select a file
errorMessages.push(message);
//$rootScope.$apply();
}
}
})();
Now the controller:
(function () {
angular
.module("cameraApp.settings")
.controller("SettingsController", SettingsController);
SettingsController.$inject = ["settingsService"];
function SettingsController(settingsService) {
var vm = this;
vm.settings = settingsService;
activate();
//////////////////
function activate(){
// Nothing here yet
}
}
})();
Finnally on the view:
<h1>{{vm.settings.overlays.dataUrl}}</h1>
<button id="overlay" class="button"
ng-click="vm.settings.selectOverlayFile()">
Browse...
</button>
Whenever I change the value in the factory, it doesn't change in the view.
Thanks in advance!
Unfortunately Factories in angularjs are not meant to be used as two way bindings. Factories and Services are only singletons. They are only there to be used when called.
Ex Factory:
app.factory('itemFactory', ['$http', '$rootScope', function($http, $rootScope) {
var service = {};
service.item = null;
service.getItem = function(id) {
$http.get(baseUrl + "getitem/" + id)
.then(function successCallback(resp) {
service.item = resp.data.Data;
$rootScope.$broadcast("itemready");
}, function errorCallback(resp) {
console.log(resp)
});
};
return service;
}]);
I use the $broadcast so if I call getItem my controller knows to go get the fresh data.
Ex Directive:
angular.module("itemApp").directive("item", ['itemFactory', '$routeParams', '$location', '$rootScope', '$timeout', function (itemFactory, $routeParams, $location, $rootScope, $timeout) {
return {
restrict: 'E',
templateUrl: "components/item.html",
link: function (scope, elem, attr) {
scope.item = itemFactory.item;
scope.changeMade = function(){
itemFactory.getItem(1);
}
scope.$on("itemready", function () {
scope.item = itemFactory.item;
})
}
}
}]);
So as you can see in my code above anytime I need a fresh item I use $broadcast and $on to update my service and directive. I hope this makes sense, feel free to ask any questions.
As pointed by Ohjay44, the factory is not updated on the view. The way to do it is using a directive (also as Ohjay44 said). To use $broadcast, $emit and $on and keep the encapsulation I did what is recommended by John Papa's Angular Style Guide: created a factory (in my case a named it comms).
Here goes the newly created directive (overlay.directive.js):
(function () {
angular
.module('cameraApp.settings')
.directive('ptrptSettingsOverlaysInfo', settingsOverlaysInfo);
settingsOverlaysInfo.$inject = ["settingsService", "comms"];
function settingsOverlaysInfo(settingsService, comms) {
var directive = {
restrict: "EA",
templateUrl: "js/app/settings/overlays.directive.html",
link: linkFunc,
controller: "SettingsController",
controllerAs: "vm",
bindToController: true // because the scope is isolated
};
return directive;
function linkFunc(scope, element, attrs, vm) {
vm.overlays = settingsService.overlays;
comms.on("overlaysUpdate", function (event, overlays) {
vm.overlays = overlays;
});
}
}
})();
I created overlay.directive.html with:
<div class="item item-thumbnail-left">
<img ng-src="{{vm.overlays.dataUrl}}">
<h2>{{vm.overlays.dataUrl}}</h2>
</div>
And finally I put an $emit on the settingsService where the overlay is updated:
(function () {
"use strict";
angular
.module("cameraApp.core")
.factory("settingsService", settingsService);
settingsService.$inject = ["comms", "$cordovaFileTransfer", "$cordovaCamera"];
function settingsService(comms, $cordovaFileTransfer, $cordovaCamera) {
var overlays = {
dataUrl: "",
options: {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
}
};
var errorMessages = [];
var service = {
overlays: overlays,
selectOverlayFile: selectOverlayFile,
errorMessages: errorMessages
};
return service;
function selectOverlayFile() {
$cordovaCamera.getPicture(overlays.options).then(successOverlay, errorOverlay);
}
//Callback functions
function successOverlay(imageUrl) {
//If user has successfully selected a file
var extension = "jpg";
var filename = getCurrentDateFileName();
$cordovaFileTransfer.download(imageUrl, cordova.file.dataDirectory + filename + '.' + extension, {}, true)
.then(function (fileEntry) {
overlays.dataUrl = fileEntry.nativeURL;
// New code!!!!
comms.emit("overlaysUpdated", overlays);
}, function (e) {
errorMessages.push(e);
});
}
function errorOverlay(message) {
//If user couldn't select a file
errorMessages.push(message);
//$rootScope.$apply();
}
}
})();
I used an $emit instead of a broadcast to prevent the bubbling as explained here: What's the correct way to communicate between controllers in AngularJS?
Hope this helps someone else too.
Cheers!
I have the following directive, service and controller inside my AngularJS app. The service is common between the directive and this controller (as well as other controllers using the same service in my app). As shown inside the controller I watch the service for changes, while in directive I communicate with the service to update it. For some reason which I don't know the directive is not updated my service, so can someone please tell me what I am doing wrong here? Thanks
Controller:
myapp.controller('ClientsCtrl', function ($scope, UserSvc) {
$scope.showForm = UserSvc.frmOpened;
$scope.$watch(function () {
return UserSvc.frmOpened;
}, function () {
$scope.showForm = UserSvc.frmOpened;
console.log('Changed... ' + $scope.showForm);
});
});
Service
myapp.factory('UserSvc', function ($log, $q, $http) {
return {
frmOpened: false
};
});
Directive:
myapp.directive('myDirective', ['UserSvc', function (UserSvc) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
angular.element(element).on("click", function () {
var parentElement = $(this).parent();
if (parentElement.hasClass('sample')) UserSvc.frmOpened = true; //This code never update the service
} else {
UserSvc.frmOpened = false; //This code never update the service
}
return false;
});
}
};
}]);
.on() is a jQuery method (also included in Angular's jqLite). The code inside the attached event handler lives outside of Angular, so you need to use $apply:
$apply() is used to execute an expression in angular from outside of
the angular framework. (For example from browser DOM events,
setTimeout, XHR or third party libraries). Because we are calling into
the angular framework we need to perform proper scope life cycle of
exception handling, executing watches.
For example:
element.on("click", function() {
var parentElement = $(this).parent();
scope.$apply(function() {
if (parentElement.hasClass('sample')) {
UserSvc.frmOpened = true;
} else {
UserSvc.frmOpened = false;
}
});
return false;
});
Demo: http://plnkr.co/edit/mCl0jFwzdKW9UgwPYSQ9?p=preview
Also, the element in the link function is already a jqLite/jQuery-wrapped element, no need to perform angular.element() on it again.
It looks like you have some brackets where they shouldn't be in your directive. You don't have brackets surrounding the first part of your if statement, but you have a closing bracket before your else. I think this messes up things.
Try using this as your link-function and see if it changes anything:
link: function (scope, element, attrs) {
angular.element(element).on("click", function () {
var parentElement = $(this).parent();
if (parentElement.hasClass('sample')) {
UserSvc.frmOpened = true; //Surrounded this with brackets
} else {
UserSvc.frmOpened = false;
}
return false;
});
}
I am trying to configure my first tidbits of the AngularJs for a trivial stuff, but unfortunately unsuccessful at it after considerable amount of time.
My Premise:
Users select one of the options from a dropdown and have an appropriate template loaded into a div below the select. I have set up the service, a custom directive (by following the ans by #Josh David Miller on this post, and a controller in place. The ajax call in service is working fine except that the params that I pass to the server is hardcoded. I want this to be the 'key' from the dropdown selected by user. At the moment I am failing to have this code passed to the service.
My configuration:
var firstModule = angular.module('myNgApp', []);
// service that will request a server for a template
firstModule.factory( 'katTplLoadingService', function ($http) {
return function() {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {params:{'b1'}}
).success(function(template, status, headers, config){
return template
})
};
});
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
// here I am unsuccessfully trying to set the user selected code to a var in service,
//var objService = new katTplLoadingService();
//objService.breedCode({code: $scope.breed.code});
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService();
}
});
firstModule.directive('showBreed', function ($compile) {
return {
scope: true,
link: function (scope, element, attrs) {
var el;
attrs.$observe( 'template', function (tpl) {
if (angular.isDefined(tpl)) {
el = $compile(tpl)(scope);
element.html("");
element.append(el);
}
});
}
};
})
and the HTML setup is
<form ng-controller="KatController">
<select name="catBreeds" from="${breedList}" ng-change="loadBreedData()"
ng-model="breed.code" />
<div>
<div show-breed template="{{template}}"></div>
</div>
</form>
I need the currently hardcoded value 'b1' in the $http ajax call to be the value in $scope.breed.code.
Your ajax request is async while your controller behaves as if the request were sync.
I assume that the get request has everything it needs to perform right.
First pass a callback to your service (note the usage of fn):
firstModule.factory( 'katTplLoadingService', function ($http) {
return {
fn: function(code, callback) { //note the callback argument
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}",
params:{code: code}}) //place your code argument here
.success(function (template, status, headers, config) {
callback(template); //pass the result to your callback
});
};
};
});
In your controller:
$scope.loadBreedData = function() {
katTplLoadingService.fn($scope.breed.code, function(tmpl) { //note the tmpl argument
$scope.template = tmpl;
});
}
Doing so your code is handling now your async get request.
I didn't test it, but it must be doing the job.
I think you defined the factory not in right way. Try this one:
firstModule.factory('katTplLoadingService', ['$resource', '$q', function ($resource, $q) {
var factory = {
query: function (selectedSubject) {
$http.get("${createLink(controller:'kats', action:'loadBreedInfo')}", {
params: {
'b1'
}
}).success(function (template, status, headers, config) {
return template;
})
}
}
return factory;
}]);
firstModule.controller('KatController', function($scope, katTplLoadingService) {
$scope.breed = {code:''}
$scope.loadBreedData = function(){
$scope.template = katTplLoadingService.query({code: $scope.breed.code});
}
});