I try to find the position of an arbitrary element inside an angular directive.
My idea was to add a class with ng-class and then use element[0].querySelector('.theClass').getBoundingClientRect(); to get the position.
The error is: Cannot read property 'getBoundingClientRect' of null.
So my suspect is, that the template of the directive is not compiled yet, such that querySelector can not find it.
So I also tried $timeout(function(){ ... }), but with the same result.
Any ideas how to find the position of an arbitrary element in angular?
The code:
'use strict';
angular.module('myApp')
.directive('myDirective', function ($timeout) {
return {
templateUrl: 'the/template',
restrict: 'EA',
scope: {
objects:"="
},
link: function (scope, element, attrs) {
$timeout(function(){
//DOM has finished rendering
var rect = element[0].querySelector('.theClass').getBoundingClientRect();
console.log('this is the element');
console.log(rect.top, rect.right, rect.bottom, rect.left);
});
}
};
});
And the template is about:
<span ng-repeat="object in objects">
<span ng-class="{'theClass':$last}"></span>
</span>
Maybe you should try to put it in postLink like :
angular.module('myApp')
.directive('myDirective', function () {
return {
templateUrl: 'the/template',
restrict: 'EA',
scope: {
objects:"="
},
link: {
post : function (scope, element, attrs) {
var rect = element[0].querySelector('.theClass').getBoundingClientRect();
console.log('this is the element');
console.log(rect.top, rect.right, rect.bottom, rect.left);
}
}
};
});
Related
I have bunch of places where I need to add ng-show to the element to hide it. Can it be done from one place in the code?
So instead of this template:
<tr my-row ng-show="$ctrl.model.toShow()"></tr>
It should be:
<tr my-row ></tr>
and then in the directive:
function myRow (){
return {
restrict: 'A',
templateUrl: 'my-row.html',
..
link = function(scope,el,attrs){
scope.$watch('modle.toShow', function(){
//something here?
})
}
};
}
Make these changes to the link function, and this adds an attribute ng-show to your my-row directive.
var app = angular.module('app', [])
.directive('myRow', function($compile) {
return {
restrict: 'A',
templateUrl: 'my-row.html',
link: function (scope, element, attrs) {
var attr;
element.attr('ng-show', true);
var fn = $compile(element);
return function(scope){
fn(scope);
};
}
};
})
HEre is the plunker
Recently I use angular to develop a directive, there is an directive which like ng-repeat to generate some records, I used transclude to implement it. but it raise an error that "Controller 'aArea', required by directive 'bSpan', can't be found!".
1. ModuleA code
var moduleA = angular.module("moduleA", []);
moduleA.directive("aArea", function () {
return {
restrict: 'E',
transclude:'element',
scope: {
amount:"="
},
template: '<div id=\"cc\" ng-transclude></div>',
controller: function ($scope,$element,$attrs) {
this.getData = function (data) {
return data + " is ok";
}
},
compile: function (tElement, attrs, linker) {
var parentElement = tElement.parent();
return {
pre: function () {
},
post: function (scope) {
linker(scope.$parent,function (clone,scope) {
parentElement.append(clone);
});
linker(scope.$parent, function (clone, scope) {
parentElement.append(clone);
});
linker(scope.$parent, function (clone, scope) {
parentElement.append(clone);
});
}
}
}
}
});
moduleA.directive("bSpan", function () {
return {
restrict: 'E',
scope: {
data: "=",
},
template: '<span style=\"background-color:gray;color:orange\">{{data}}</span>',
require: "^aArea",
link: function ($scope, $element, $attrs, controller) {
var data = "abc";
}
}
});
2. ModuleB COde
var moduleB = angular.module("moduleB", []);
moduleB.directive("myItem", function () {
return {
restrict: 'E',
scope: {
item: "=",
itemTemplate: '='
},
priority: 1000,
terminal:false,
template: '<ng-include src=\"itemTemplate\"/>',
controller: function ($scope, $element, $attrs) {
var data = "";
}
}
})
3. ModuleC Code
var moduleC = angular.module("moduleC", ["moduleA", "moduleB"]);
moduleC.controller("Ctr", function ($scope) {
$scope.item = {};
$scope.item.dataAmount = 1000;
$scope.item.templateUrl = "item-template.html";
})
4. Html Code
<body>
<div ng-app="moduleC">
<div ng-controller="Ctr">
<a-area>
<my-item item="item" item-template="item.templateUrl"></my-item>
</a-area>
</div>
</div>
</body>
5. template code
<div>
<span style="display:block">hello every one</span>
<b-span data="item.dataAmount"></b-span>
</div>
You should not use the transclude function (that you called linker) of the compile function - it is deprecated.
From $compile documentation:
Note: The transclude function that is passed to the compile function is deprecated, as it e.g. does not know about the right outer scope. Please use the transclude function that is passed to the link function instead.
Following this guidance (and a few other minor changes for the better), change the aArea directive as follows:
compile: function(tElement, tAttrs) {
// don't use the template element
//var parentElement = tElement.parent();
return function(scope, element, attrs, ctrls, transclude) {
transclude(function(clone, scope) {
element.after(clone);
});
transclude(function(clone, scope) {
element.after(clone);
});
transclude(function(clone, scope) {
element.after(clone);
});
};
}
In fact, you don't even need the transclude function at all and you don't need to do transclude: "element". You could just change to transclude: true and use <div ng-transclude> 3 times in the template.
I want to create two directives that have the following structure:
<div ng-app="myApp">
<div ui-foo="test">
<div ui-bar="test2"></div>
</div>
</div>
First directive is uiFoo, the second one is uiBar.
To define these directives I have setup the following module definition:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
}
};
}
).directive('uiBar',
function() {
return {
restrict: 'A',
require: '^uiFoo',
scope: true,
link: function($scope, element, attrs, uiBarController) {
uiBarController.message();
}
};
}
);
angular.module('myApp', ['ui']);
The problem that I am experiencing is known as error/$compile/ctreq (Controller 'uiFoo', required by directive 'uiBar', can't be found!) and the documentation for it can be found here (https://docs.angularjs.org/error/$compile/ctreq?p0=uiFoo&p1=uiBar). I know, a little lackluster.
It doesn't seem to solve my issue.
I've created a JSFiddle for this which you can find here http://jsfiddle.net/A8Vgk/1187/
Thanks!
Like the error says, you're missing the controller on the uiFoo directive.
When you use the require: ^uiFoo, it tells Angular that you want to have access to the controller in the directive called uiFoo.
You didn't define a controller in that directive, so you get the error.
Just define the controller:
angular.module('ui', []).directive('uiFoo',
function() {
return {
restrict: 'A',
link: function($scope, element, attrs) {
$scope.message = function() {
alert(1);
};
},
controller: function($scope) {
this.message = function () {
alert("works!");
}
}
};
}
)
Working Fiddle.
I have a setup like this:
<controller>
<directive>
in my controller that has a function that returns an html string. How can I get my directive to render this by accessing the controllers scope?
Or maybe I should just put the controller in the directive?
app.controller('controller', ['$scope', 'DataService', function ($scope, DataService) {
$scope.parseJson = function () {
//returns the html
};
}]);
directive
app.directive('Output', function () {
return {
restrict: 'A',
replace: true,
template: '<need html from controller>',
link: function(scope, element, attr) {
//render
//scope.parseJson();
}
};
});
You should use the isolated scope: '&' option
app.directive('output', ['$sce', function ($sce) {
return {
restrict: 'A',
replace: true,
template: "<div ng-bind-html='parsed'></div>",
scope:{
output: "&"
},
link: function(scope){
scope.parsed = $sce.trustAsHtml(scope.output());
}
};
}]);
Template:
<div output="parseJson()"></div>
The directive and the controller should be sharing the scope already. Don't bother using a template for the directive, just get the HTML string in you linking function (you already have the method call in there) and modify the element directly using element.html(). Take a look at the element docs for more info.
app.directive('Output', function ($compile) {
return {
restrict: 'A',
link: function(scope, element, attr) {
var templateString = scope.parseJson();
var compiledTemplate = $compile(templateString)(scope);
compiledTemplate.appendTo("TheElementYouWishtoAppendYourDirectiveTo");
}
};
});
I'm trying to acheive databinding to a value returned from a service inside a directive.
I have it working, but I'm jumping through hoops, and I suspect there's a better way.
For example:
<img my-avatar>
Which is a directive synonymous to:
<img src="{{user.avatarUrl}}" class="avatar">
Where user is:
$scope.user = CurrentUserService.getCurrentUser();
Here's the directive I'm using to get this to work:
.directive('myAvatar', function(CurrentUser) {
return {
link: function(scope, elm, attrs) {
scope.user = CurrentUser.getCurrentUser();
// Use a function to watch if the username changes,
// since it appears that $scope.$watch('user.username') isn't working
var watchUserName = function(scope) {
return scope.user.username;
};
scope.$watch(watchUserName, function (newUserName,oldUserName, scope) {
elm.attr('src',CurrentUser.getCurrentUser().avatarUrl);
}, true);
elm.attr('class','avatar');
}
};
Is there a more succinct, 'angular' way to achieve the same outcome?
How about this ? plunker
The main idea of your directive is like
.directive('myAvatar', function (CurrentUserService) {
"use strict";
return {
restrict: 'A',
replace: true,
template: '<img class="avatar" ng-src="{{url}}" alt="{{url}}" title="{{url}}"> ',
controller: function ($scope, CurrentUserService) {
$scope.url = CurrentUserService.getCurrentUser().avatarUrl;
}
};
});