I have a directive which is working correctly when coded this way:
return {
restrict: 'E',
transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this.
scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.
priceinformation: '=priceinformation'
},
controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) {
var controller={
_$state:$state,
pricinginfo: [],
};
//console.log(PriceCalculatorService);
//debugger;
PriceCalculatorService.getPricingInfo()
.success(function (result) {
controller.pricinginfo = result;
})
.error(_handleError);
function _handleError(error) {
controller.error = error;
controller._$state.go('error-404');
}
$scope.controller = controller;
return controller;
}],
templateUrl: 'app/common/directives/views/price-calculator.html',
However, I want to isolate the controller, and do it this way instead:
(function (app) {
'use strict';
// #see https://docs.angularjs.org/guide/directive
// #important: Requires an object named pricinginformation is pushed into the directive.
var PriceCalculatorControl = (function () {
// scope is an isolated part of $scope limited this control only so we don't put a $
var PriceCalculatorControl = ['scope','PriceCalculatorService', function PriceCalculatorControl(scope,PriceCalculatorService) {
var control = {
total: 0,
subscriptionUnitprice: 100,
totalcal: function totalcal() {
if (scope.priceinformation.subscriptioninfo.type == 'Daily') {
control.subscriptionUnitprice = 100;
}
else if (scope.priceinformation.subscriptioninfo.type == 'Monthly') {
control.subscriptionUnitprice = 500;
}
else {
control.subscriptionUnitprice = 100;
}
control.total = control.subscriptionUnitprice * scope.priceinformation.subscriptioninfo.period * scope.priceinformation.subscriptioninfo.subjectsselected;
}
};
//kicking off the service
PriceCalculatorService.getPricingInfo()
.success(function (result) {
controller.pricinginfo = result;
})
.error(_handleError);
function _handleError(error) {
controller.error = error;
controller._$state.go('error-404');
}
// bootstrap
/* When injecting stuff, clean them up here. Like a timer that's running needs to be stopped.
element.on('$destroy', function() {});*/
//register on scope
scope.PriceCalculatorControl.PriceCalculatorControl;
}];
PriceCalculatorControl[2]();
return {
restrict: 'E',
transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this.
scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.
priceinformation: '=priceinformation'
},
//controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) {
// var controller={
// _$state:$state,
// pricinginfo: [],
// };
// //console.log(PriceCalculatorService);
// //debugger;
// PriceCalculatorService.getPricingInfo()
// .success(function (result) {
// controller.pricinginfo = result;
// })
// .error(_handleError);
// function _handleError(error) {
// controller.error = error;
// controller._$state.go('error-404');
// }
// $scope.controller = controller;
// return controller;
//}],
templateUrl: 'app/common/directives/views/price-calculator.html',
link: PriceCalculatorControl
};
});
// Register the directive
app.directive('priceCalculator', PriceCalculatorControl);
})(angular.module('app.common'));
This second method is not working. scope.PriceCalculatorControl.PriceCalculatorControl; says PriceCalculatorControl is not define.
PriceCalculatorService.getPricingInfo() says getPricingInfo is not defined.
Note: the service is working correctly. I guess the problem has to do with the dependency injection, but can't figure out what. Kindly enlighten me.
Thanks.
Try this:
(function (app) {
'use strict';
// #see https://docs.angularjs.org/guide/directive
// #important: Requires an object named pricinginformation is pushed into the directive.
var PriceCalculatorControl = (['PriceCalculatorService', function (PriceCalculatorService) {
// scope is an isolated part of $scope limited this control only so we don't put a $
var PriceCalculatorControl = function PriceCalculatorControl(scope) {
var control = {
total: 0,
subscriptionUnitprice: 100,
totalcal: function totalcal() {
if (scope.priceinformation.subscriptioninfo.type == 'Daily') {
control.subscriptionUnitprice = 100;
}
else if (scope.priceinformation.subscriptioninfo.type == 'Monthly') {
control.subscriptionUnitprice = 500;
}
else {
control.subscriptionUnitprice = 100;
}
control.total = control.subscriptionUnitprice * scope.priceinformation.subscriptioninfo.period * scope.priceinformation.subscriptioninfo.subjectsselected;
}
};
//kicking off the service
PriceCalculatorService.getPricingInfo()
.success(function (result) {
controller.pricinginfo = result;
})
.error(_handleError);
function _handleError(error) {
controller.error = error;
controller._$state.go('error-404');
}
// bootstrap
/* When injecting stuff, clean them up here. Like a timer that's running needs to be stopped.
element.on('$destroy', function() {});*/
//register on scope
scope.PriceCalculatorControl.PriceCalculatorControl;
};
//PriceCalculatorControl[2]();
return {
restrict: 'E',
transclude: true, //transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. So we can access the vm calling this.
scope: { // As the name suggests, the isolate scope of the directive isolates everything except models that you've explicitly added to the scope: {} hash object. This is helpful when building reusable components because it prevents a component from changing your model state except for the models that you explicitly pass in.
priceinformation: '=priceinformation'
},
//controller: ['$scope','PriceCalculatorService', '$state', function ($scope,PriceCalculatorService, $state) {
// var controller={
// _$state:$state,
// pricinginfo: [],
// };
// //console.log(PriceCalculatorService);
// //debugger;
// PriceCalculatorService.getPricingInfo()
// .success(function (result) {
// controller.pricinginfo = result;
// })
// .error(_handleError);
// function _handleError(error) {
// controller.error = error;
// controller._$state.go('error-404');
// }
// $scope.controller = controller;
// return controller;
//}],
templateUrl: 'app/common/directives/views/price-calculator.html',
link: PriceCalculatorControl
};
}]);
// Register the directive
app.directive('priceCalculator', PriceCalculatorControl);
})(angular.module('app.common'));
Also I'm not sure what this is supposed to achieve:
PriceCalculatorControl[2]();
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 got a component with an animation defined as such:
angular
.module('slider')
.component('slider', {
templateUrl: '/mytemplate.html',
controller: function SliderController() {
var self = this;
self.direction = 'left';
}
})
.animation('.slide-animation', function() {
return {
beforeAddClass: function (element, className, done) {
var scope = element.scope();
// The line below logs undefined???
console.log(scope.direction);
}
};
});
I'm trying to access a value from the controller's scope but it's being returned as undefined which leads me to believe I've got the wrong scope. Is that correct? How can I get the controller's scope from within the animation?
I was able to get the scope I was looking for with help from Genti's comment.
angular
.module('slider')
.component('slider', {
templateUrl: '/mytemplate.html',
controller: function SliderController() {
var self = this;
self.direction = 'left';
}
})
.animation('.slide-animation', function() {
return {
beforeAddClass: function (element, className, done) {
var scope = element.scope().$ctrl;
console.log(scope.direction);
}
};
});
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 a value named $scope.title in my controller. This value is initialized with $scope.title = 'global.loading';. I have a factory named Product.
My view is calling a directive via <menu-top ng-title="title"></menu-top>, the view of this directive is <span>{{title|translate}}</span>.
When I want to get a product I do : Product.get(id). Their is two possibility.
First one (working) -> My product is cached in localstorage and my title in the directive is uptated.
Second one (not working) -> My product is not cached, I call my WebService, put the response in cache and return the response. In this case, the title is updated (console.log) in the controller, but not in my directive ...
angular.module('angularApp')
.directive('menuTop', function () {
return {
templateUrl: 'views/directives/menutop.html',
restrict: 'E',
scope:{
ngTitle: '=?'
},
link: function postLink(scope) {
scope.title = scope.ngTitle;
}
};
});
angular.module('angularApp')
.controller('ProductCtrl', function ($scope, $routeParams, Product) {
$scope.productId = parseInt($routeParams.product);
$scope.title = 'global.loading';
$scope.loading = true;
$scope.error = false;
$scope.product = null;
Product
.get($scope.productId)
.then(function(product){
$scope.loading = false;
$scope.title = product.name;
$scope.product = product;
}, function(){
$scope.error = true;
$scope.loading = false;
})
;
});
angular.module('angularApp')
.factory('Product', function ($http, responseHandler, ApiLink, LocalStorage, $q) {
var _get = function(id) {
return $q(function(resolve, reject) {
var key = 'catalog/product/' + id;
var ret = LocalStorage.getObject(key);
if (ret) {
return resolve(ret);
}
responseHandler
.handle($http({
method: 'GET',
url: ApiLink.get('catalog', 'product', {id: id})
}))
.then(function(response) {
if (response.product && response.product.name) {
LocalStorage.putObject(key, response.product, 60 * 5);
return resolve(response.product);
}
reject(null);
}, function() {
reject(null);
});
});
};
return {
'get': _get
};
});
Thank you for your help !
As Sergio Tulentsev suggested, you can use '#' as binding method.
Using # will interpolate the value. It means that you can use it as a readonly this way : ng-title="{{mytitle}}"
angular.module('angularApp')
.directive('menuTop', function () {
return {
templateUrl: 'views/directives/menutop.html',
restrict: 'E',
scope:{
ngTitle: '#'
},
link: function postLink(scope) {
scope.title = scope.ngTitle;
}
};
});
Also keep in mind that you shouldn't use "ng" for your custom directives. ng is used for angular natives components. You can (should) keep this naming convention with your application name. Like for an application "MyStats" your could name your components ms-directivename
If you need more informations about the directives bindings you can refer to this documentation
Reference: Unit Testing AngularJS Directives: scopes not updating?
Case
I have a directive called editable that take an ng-model and creates a toggleable/editable field. The directive works and the parent scope is updated correctly, there are no problems in the actual function of the directive. I cannot seem to write a test that supports this though. It took me a long time to get the directive working properly with all the caveats so I really want to get some tests in place to make sure it continues to work in all of the different cases.
The Directive (which works)
I can't be sure which pieces will be relevant so i included the whole thing.
app.directive('editable',
['$templateCache', '$compile',
function ($templateCache, $compile) {
return {
restrict: 'A',
transclude: true,
templateUrl: 'template/directives/editable.html',
replace: true,
require: 'ngModel',
scope: true,
compile: function(element, attrs, transcludeFn) {
return function (scope, iElement, iAttrs, ctrl) {
var validityId = 'editable-' + scope.$id;
scope.lastSavedValue = iElement.find('input').val();
scope.storeValue = function() {
scope.lastSavedValue = iElement.find('input').val();
};
scope.edit = function() {
scope.storeValue();
scope.editing = true;
$('input', iElement).focus().select();
ctrl.$setValidity(validityId, true);
};
scope.ok = function() {
var inputCtrl = iElement.find('input').controller('ngModel');
if(inputCtrl.$valid === true) {
scope.editing = false;
scope.value = inputCtrl.$viewValue;
ctrl.$setValidity(validityId, false);
ctrl.$setViewValue(inputCtrl.$viewValue); // Not sure (why) this is needed
}
};
scope['delete'] = function() {
scope.deleted = true;
scope.editing = false;
};
scope.undo = function() {
var inputCtrl = iElement.find('input').controller('ngModel');
if(scope.lastSavedValue) {
inputCtrl.$setViewValue(scope.lastSavedValue);
scope.value = scope.lastSavedValue;
ctrl.$setViewValue(scope.lastSavedValue);
}
iElement.find('input').val(scope.value);
scope.editing = false;
scope.deleted = false;
ctrl.$setValidity(validityId, false);
};
transcludeFn(scope, function(clone) {
var $editingReplacement = $(clone).filter('[editing]');
var $viewingReplacement = $(clone).filter('[viewing]');
var $deletedReplacement = $(clone).filter('[deleted]');
var $viewingControls = $('.editable-view-container .controls', iElement);
var $editingControls = $('.editable-input-container .controls', iElement);
var $deletedControls = $('.editable-delete-container .controls', iElement);
if($editingReplacement.length) {
$('.editable-input-container', iElement).html($editingReplacement.html());
$('.editable-input-container', iElement).append($editingControls);
$compile($('.editable-input-container', iElement))(scope);
} else {
$('.editable-input-container', iElement).find('input').attr('ng-model', iAttrs['ngModel']);
$compile($('.editable-input-container', iElement))(scope);
}
if($viewingReplacement.length) {
$('.editable-view-container', iElement).html($viewingReplacement.html());
$('.editable-view-container', iElement).append($viewingControls);
$compile($('.editable-view-container', iElement))(scope);
}
if($deletedReplacement.length) {
$('.editable-delete-container', iElement).html($deletedReplacement.html());
$('.editable-delete-container', iElement).append($deletedControls);
}
});
/**
* Deleted (Isolated Scope)
*
* Tracks if the user has clicked the delete button
*
* #type {Boolean}
*/
scope.deleted = false;
/**
* Editing (Isolated Scope)
*
* Tracks the state of the view
*
* #type {Boolean}
*/
scope.editing = false;
/**
* Initial Loader
*
* Run once after ctrl is loaded
*
* #return {[type]} [description]
*/
var unbindWatcher = scope.$watch(function() { return ctrl.$modelValue; }, function(newVal, oldVal) {
if(typeof ctrl.$modelValue !== 'undefined') {
scope.value = ctrl.$modelValue;
scope.editing = ctrl.$modelValue ? false : true;
unbindWatcher();
}
});
};
}
};
}
]);
Spec
Fails at the end
describe('Editable Directive', function() {
// Keep references to element and scope so that they are available to all tests
var element, scope, ctrl;
beforeEach(module('ltAccountApp'));
beforeEach(module('templates'));
beforeEach(inject(function ($rootScope, $compile) {
var linkFn, el;
// scope = $rootScope;
scope = $rootScope.$new();
scope.testValue = 'xxx';
el = angular.element('\
<div editable="" ng-model="testValue"></div>\
');
// The $compile method returns the directive's link function
linkFn = $compile(el);
// The link function returns the resulting DOM object
element = linkFn(scope);
element.scope().$apply();
ctrl = element.controller('ngModel');
}));
it('should assign input value to scope value', function() {
expect(element.find('input').val()).toEqual(scope.testValue);
});
it('should have access to parent scope variable passed into directive', function() {
expect(ctrl.$viewValue).toEqual(scope.testValue);
expect(ctrl.$modelValue).toEqual(scope.testValue);
});
it('should manage state editing correctly', function() {
expect(element.scope().editing).toBe(false);
element.scope().edit();
expect(element.scope().editing).toBe(true);
});
it('should manage state deleted correctly', function() {
expect(element.scope().deleted).toBe(false);
element.scope()['delete']();
expect(element.scope().deleted).toBe(true);
});
it('should be able to modify parent scope variable passed into directive', function() {
// Not sure what this does, added from referenced SO question
// spyOn(scope, '$apply').andCallThrough();
var newValue = 'yyy';
element.scope().edit();
element.find('input').val(newValue);
element.find('input').trigger('input');
element.scope().ok();
expect(ctrl.$viewValue).toEqual(newValue);
expect(ctrl.$modelValue).toEqual(newValue);
expect(element.scope().value).toEqual(newValue);
expect(scope.$apply).toHaveBeenCalled();
expect(scope.testValue).toEqual(newValue); // <-fails
});
});
So...
Everything seems to be working until I actually expect the parent scope to have the changed value.
I know there is a lot here, I appreciate any guidance you can provide.
Plunk of Angular + Jasmine with directive (work in progress)
Lets say you have to update the value of input field to 'kasrak'. Trying doing it like this:
var elm = element.find("input");
elm.val('kasrak');
elm.trigger($sniffer.hasEvent('input') ? 'input' : 'change');
$scope.$digest()
Key is the third line with $sniffer service. I found this in angular-ui's bootstrap tests.
Here is the link to the function in test spec: https://github.com/angular-ui/bootstrap/blob/master/src/typeahead/test/typeahead.spec.js#L31