I'm in the middle of refactoring an old project to use custom directives, and I'm already running into a problem. I'm just trying to make a simple directive and build from there. I have a logger function in my directive's link function that just runs a console.log. I'm not sure what I'm missing here, and I'm sure it's something simple. Here's my directive:
'use strict';
(function() {
angular
.module('sigFig')
.directive('myDirective', myDirective);
function myDirective(sigFigFactory) {
var directive = {
restrict: 'E',
replace: 'true',
templateUrl: 'Directives/directiveTemplate.html',
link: link,
compile: compile
};
return directive;
function link(scope, element, attrs) {
scope.logger = function() {
console.log('DING!!!');
}
}
function compile(scope, element, attrs) {
console.log('I AM A COMPILE FUNCTION');
}
}
})();
The HTML template for it is just:
<button ng-click="logger()">CLICK ME</button>
And I'm calling it in my HTML like this:
<my-directive></my-directive>
The button appears and that console.log in my compile works, but the ng-click does not. What is it I'm missing? Thanks in advance!
Add scope to directive variable: scope:{},
function myDirective(sigFigFactory) {
var directive = {
scope:{},
restrict: 'E',
replace: 'true',
templateUrl: 'Directives/directiveTemplate.html',
link: link,
compile: compile
};
return directive;
I have never created an angular application without a controller. So I'm positive that that is your issue here.
Example of your code with a controller.
html:
<body ng-app='sigFig' ng-controller='ctrl'>
<my-directive></my-directive>
</body>
js:
(function() {
angular.module('sigFig', [])
.controller('ctrl', function($scope){
$scope.itemH = 'hahaha'
})
.directive('myDirective', myDirective);
function myDirective() {
return {
restrict: 'E',
template: '<button ng-click="logger()">{{item}}</button>',
link: function link(scope, element, attrs) {
scope.item = "Logger Click Me";
scope.logger = function() {
alert('logger')
}
}
};
function compile(scope, element, attrs) {
console.log('I AM A COMPILE FUNCTION');
}
}
})();
I have written a directive by using typescript. here is my directive below.
'use strict';
module App.Directives {
interface IPageModal extends ng.IDirective {
}
interface IPageModalScope extends ng.IScope {
}
class PageModal implements IPageModal {
static directiveId: string = 'pageModal';
restrict: string = "A";
constructor(private $parse: ng.IParseService) {
}
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);
fn(scope, { $event: event });
});
}
}
//References angular app
app.directive(PageModal.directiveId, ['$parse', $parse => new PageModal($parse)]);
}
Use in HTML
<button class="btn blue-grey-900" target-modal="emplpyeeViewModal" page-modal="vm.addEmployee($event)">
<i class="icon-plus m-b-xs"></i>
</button>
Use in Controller
addEmployee($event) {
$event.openModal();
};
This line does not work. var fn = this.$parse(attrs['pageModal']); . I can not understand what is wrong. The error is
this.$parse is undefined.
and Service is called two times
It's quite trivial: your this is not your class'es scope because the function openmodal(event) { defines its own.
Declare the function on a class level or use arrow function instead, e.g.
link = (scope: IPageModalScope, element, attrs) => {
element.click((event) => {
event.preventDefault();
var options = {
backdrop: 'static',
keyboard: false
};
event.openModal = function () {
$('#' + attrs['targetModal']).modal(options);
};
event.showModal = function () {
$('#' + attrs['targetModal']).modal('show');
};
event.closeModal = function () {
$('#' + attrs['targetModal']).modal('hide');
};
var fn = this.$parse(attrs['pageModal']);//does not work here
fn(scope, { $event: event });
});
}
I have a view with a ui.bootstrap modal that has its own controller.
In the view, i have a directive that generates a number of buttons with a unique ID.
I want to be able to click on one of the buttons generated and call the main view's controller to launch the modal.
Here is the main view module:
/* global angular */
angular.module('my.jobs', [
'ui.router',
'ui.bootstrap'
])
.controller('DashboardJobsCtrl', function DashboardJobsController($rootScope, $scope, $log, $state, $modal) {
var self = this;
angular.extend(this, {
displayReceipt: function(jobId) {
var modalInstance = $modal.open({
animation: true,
templateUrl: 'receiptModal.html',
size: 'lg',
controller: function($scope, $modalInstance, jobsService) {
//CODE HERE FOR ADDING VALUES TO THE MODAL...
$scope.clear = function() {
$modalInstance.close();
};
}
});
}
});
});
Here is the directive:
angular.module('jobView', ['ui.router', 'ui.bootstrap'])
.directive('jobView', function($compile, $http, $templateCache, DOMAINS) {
return {
restrict: 'E',
scope: {
job: '=',
view: '#'
},
template: 'myTemplate.html',
link: function($scope, element, attrs) {
//ASSUME THERE IS CODE HERE FOR GENERATING UNIQUE ID FOR JOBS
//NEXT LINE I WANT TO CALL MODAL FROM THE MAIN VIEW MODULE
$scope.displayReceipt('jobId')
}
};
});
I know this is a simple scope issue, but it's driving me nuts that I can't make the connection.
Here is the perfect example. calling method of parent controller from a directive in AngularJS.
I have update your example below.
<job-View updateParent='displayReceipt()'></job-View>
angular.module('jobView', ['ui.router', 'ui.bootstrap'])
.directive('jobView', function($compile, $http, $templateCache, DOMAINS) {
return {
restrict: 'E',
scope: {
job: '=',
view: '#',
updateParent:'&'
},
template: 'myTemplate.html',
link: function($scope, element, attrs) {
//ASSUME THERE IS CODE HERE FOR GENERATING UNIQUE ID FOR JOBS
//NEXT LINE I WANT TO CALL MODAL FROM THE MAIN VIEW MODULE
$scope.displayReceipt('jobId')
}
};
});
I have a directive
configModule.directive('iMemoryDiv',function () {
return {
restrict: 'E',
scope: {},
replace: true,
templateUrl: '/memoryDiv.html',
link: function(scope, el, attrs) {
scope.iObj = scope.$parent[attrs.bIObject];
if(angular.isDefined(scope.iObj)){
getSummary(scope.iObj);
}
function getSummary(iObj){
}
}
};
}
);
and I am calling it from html by passing an object attribute
<i-memory-div b-i-object="app"></i-memory-div> //here app is declared in a respective controller
but, here directive is getting loaded before the controller where value for 'app' is getting assigned.So scope.iObj = scope.$parent[attrs.bIObject] is always giving me undefined.
How can make directive load after the app value is getting assigned ??
Isn't it easier doing it this way:
configModule.directive('iMemoryDiv',function () {
return {
restrict: 'E',
scope: {
'bIObject': '=',
'getParentObject': '&'
},
replace: true,
templateUrl: '/memoryDiv.html',
link: function(scope, el, attrs) {
scope.$watch('bIObject', function(newValue) {
if(angular.isDefined(newValue)) {
getSummary(scope.getParentObject({name: newValue}));
}
});
function getSummary(iObj){
}
}
};
}
Or do you need more from the parent scope??
You could give your directive an isolated scope and add bIObject as a scope property:
scope: {
bIObject: '=',
},
you could then put your code in the controller: rather than link:
Use $observe service in link function,like this
if(attrs. bIObject) {
attrs.$observe('bIObject', function(value) {
console.log(value);
})
}
I am currently adding some bootstrap tooltips in my application.
All of the "normal" tooltips are ok, but when I want to use tooltip-html-unsafe, all I got is an empty tooltip.
My tooltip:
<a><span tooltip-placement="right" tooltip-html-safe="{{myHTMLText}}"> Help </span></a>
In the DOM, I have:
<div class="tooltip-inner" ng-bind-html-unsafe="content"></div>
The div's content seems empty, so there is nothing to show in the tooltip. I tried to put directly in the DOM some HTML text like:
<div class="tooltip-inner" ng-bind-html-unsafe="content"><b>test</b></div> and it works.
Do you have an idea?
The html-unsafe directive is designed to point at it's content. What about this:
<div data-ng-controller="SomeCtrl">
<span data-tooltip-html-unsafe="{{yourContent}}" data-tooltip-placement="right">
Help
</span>
</div>
Then, in SomeCtrl, make a variable to hold the html:
$scope.yourContent = "<b>my html, yay</b>
IF you would like to modify bootstrap to take the content from a element, it can be done like this. First, you must change the tooltip template so that it calls a function to get the html:
angular.module("template/tooltip/tooltip-html-unsafe-popup.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/tooltip/tooltip-html-unsafe-popup.html",
"<div class=\"tooltip {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"tooltip-arrow\"></div>\n" +
" <div class=\"tooltip-inner\" ng-bind-html-unsafe=\"getToolTipHtml()\"></div>\n" +
"</div>\n" +
"");
}]);
Then, make a link function for the tooltipHtmlUnsafePopup:
.directive( 'tooltipHtmlUnsafePopup', function () {
return {
restrict: 'E',
replace: true,
scope: { content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html',
link: function(scope, element, attrs) {
scope.getTooltipHtml = function() {
var elemId = '#' + scope.content;
var htmlContent = $rootElement.find(elemId).html();
return htmlContent;
};
}
};
})
EDIT: Later I extracted the customized code from ui-bootstrap, which is good since you do not have to modify ui-bootstrap to use it now. Here is the extracted code, in a module called "bootstrapx". This is just for popovers (as I was not really using tooltips) but I feel like this should be easily adaptable for tooltips too.
angular.module("bootstrapx", ["bootstrapx.tpls","bootstrapx.popover","bootstrapx.popover.dismisser"]);
angular.module("bootstrapx.tpls", ["template/popover/popover-html.html","template/popover/popover-html-unsafe.html","template/popover/popover-template.html"]);
angular.module( 'bootstrapx.popover', [ 'ui.bootstrap.tooltip' ] )
.directive('popover', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverHtml', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverHtmlUnsafe', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive('popoverTemplate', [ function() {
return {
restrict: 'EA',
priority: -1000,
link: function(scope, element) {
element.addClass('popover-link');
}
};
}])
.directive( 'popoverHtmlPopup', [ function() {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-html.html'
};
}])
.directive( 'popoverHtml', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverHtml', 'popover', 'click' );
}])
.directive( 'popoverHtmlUnsafePopup', [ '$rootElement', function ( $rootElement ) {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-html-unsafe.html',
link: function(scope, element) {
var htmlContent = '';
scope.$watch('content', function(value) {
if (!value) {
return;
}
var elemId = '#' + value;
htmlContent = $rootElement.find(elemId).html();
});
scope.getPopoverHtml = function() {
return htmlContent;
};
}
};
}])
.directive( 'popoverHtmlUnsafe', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverHtmlUnsafe', 'popover', 'click' );
}])
.directive( 'popoverTemplatePopup', [ '$http', '$templateCache', '$compile', '$parse', function ( $http, $templateCache, $compile, $parse) {
return {
restrict: 'EA',
replace: true,
scope: { title: '#', content: '#', placement: '#', animation: '&', isOpen: '&' },
templateUrl: 'template/popover/popover-template.html',
link: function(scope, element, attrs) {
scope.getPopoverTemplate = function() {
var templateName = scope.content + '.html';
return templateName;
};
}
};
}])
.directive( 'popoverTemplate', [ '$compile', '$timeout', '$parse', '$window', '$tooltip', function ( $compile, $timeout, $parse, $window, $tooltip ) {
return $tooltip( 'popoverTemplate', 'popover', 'click' );
}]);
angular.module("template/popover/popover-html.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-html.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind-html=\"content\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover-html-unsafe.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-html-unsafe.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-bind-html-unsafe=\"{{getPopoverHtml()}}\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module("template/popover/popover-template.html", []).run(["$templateCache", function($templateCache) {
$templateCache.put("template/popover/popover-template.html",
"<div class=\"popover {{placement}}\" ng-class=\"{ in: isOpen(), fade: animation() }\">\n" +
" <div class=\"arrow\"></div>\n" +
"\n" +
" <div class=\"popover-inner\">\n" +
" <h3 class=\"popover-title\" ng-bind=\"title\" ng-show=\"title\"></h3>\n" +
" <div class=\"popover-content\" ng-include=\"getPopoverTemplate()\"></div>\n" +
" </div>\n" +
"</div>\n" +
"");
}]);
angular.module('bootstrapx.popover.dismisser', [])
.directive( 'dismissPopovers', [ '$http', '$templateCache', '$compile', '$parse', function ( $http, $templateCache, $compile, $parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('mouseup', function(e) {
var clickedOutside = true;
$('.popover-link').each(function() {
if ($(this).is(e.target) || $(this).has(e.target).length) {
clickedOutside = false;
return false;
}
});
if ($('.popover').has(e.target).length) {
clickedOutside = false;
}
if (clickedOutside) {
$('.popover').prev().click();
}
});
}
};
}]);
I have the dismissPopovers directive on the body tag (this is likely applicable for tooltips too, you will just have to modify it to suit your needs):
<body data-ng-controller="AppController" data-dismiss-popovers>
I have created custom directive which allows html tooltips for bootsrap in very simple way. No need to override any templates:
angular.module('vermouthApp.htmlTooltip', [
])
.directive('vaTooltip', ['$http', '$templateCache', '$compile', '$parse', '$timeout', function ($http, $templateCache, $compile, $parse, $timeout)
{
//va-tooltip = path to template or pure tooltip string
//tooltip-updater = scope item to watch for changes when template has to be reloaded [optional (only if template is dynamic)]
//All other attributes can be added for standart boostrap tooltip behavior (ex. tooltip-placement)
return {
restrict: 'A',
scope: true,
compile: function (tElem, tAttrs)
{
//Add bootstrap directive
if (!tElem.attr('tooltip-html-unsafe'))
{
tElem.attr('tooltip-html-unsafe', '{{tooltip}}');
}
return function (scope, element, attrs)
{
scope.tooltip = attrs.vaTooltip;
var tplUrl = $parse(scope.tooltip)(scope);
function loadTemplate()
{
$http.get(tplUrl, { cache: $templateCache }).success(function (tplContent)
{
var container = $('<div/>');
container.html($compile(tplContent.trim())(scope));
$timeout(function ()
{
scope.tooltip = container.html();
});
});
}
//remove our direcive to avoid infinite loop
element.removeAttr('va-tooltip');
//compile element to attach tooltip binding
$compile(element)(scope);
if (angular.isDefined(attrs.tooltipUpdater))
{
scope.$watch(attrs.tooltipUpdater, function ()
{
loadTemplate();
});
} else
{
loadTemplate();
}
};
}
};
}]);
Thats how you call it
<a va-tooltip="'tooltipContent.html'" tooltip-updater="item" tooltip-placement="bottom">
<b><i>{{item.properties.length - propertyShowLimit + ' properties more...'}}</i></b>
</a>
And template can be like this:
<script id="tooltipContent.html" type="text/ng-template">
<span ng-repeat="prop in item.properties>
<b>{{prop.name}}</b>:
<span ng-repeat="val in prop.values">{{val.value}} </span>
<br />
</span>
</script>
There is now buit-in template functionality: https://angular-ui.github.io/bootstrap/#tooltip
Custom template
<script type="text/ng-template" id="myTooltipTemplate.html">
<span>Special Tooltip with <strong>markup</strong> and {{ dynamicTooltipText }}</span>
</script>