I am working on a directive in an AngularJS project. In this directive, I HAVE to programmatically set the width of an HTML element at runtime. However, I am not having any success in doing so. Currently, my directive looks like this:
myApp.directive('myDirective', function () {
return {
restrict:'E',
transclude: true,
templateUrl: 'my-directive.html',
link: function(scope, element, attrs) {
var inputField = element.find('input');
scope.width = inputField[0].offsetWidth;
scope.err1 = 'none';
try {
var testDiv = element.find('#test-name');
element(testDiv).css('width', (scope.width + 'px'));
} catch (e1) {
scope.err1 = e1.message;
}
scope.err2 = 'none';
try {
var testDiv = element.find('.test-class');
element(testDiv).css('width', '500px');
} catch (e2) {
scope.err2 = e2.message;
}
},
controller: function ($scope) {
}
};
});
As the plunkr shows, I get a runtime error when I attempt to programmatically set the width of my div. I do not understand what I'm doing wrong. Can somebody please show me what I'm doing wrong? I need to figure out how to set the width at runtime in either the link or controller function. Once again, I have to do this programmatically. I cannot add a width to the scope and bind the UI to it.
Here you go.
you have a few issues. First off there isn't an element with id
test-name
- you had the name
set, not the ID
.
Also, find()
will not work, use children()
instead - your example wasn't actually finding the element, hence getting the error you had.
New directive (removed your error stuff for clarity) - you can change/remove the second scope.width just to see it working
var myApp = angular.module("myApp", []);
myApp.directive('myDirective', function () {
return {
restrict:'E',
transclude: true,
templateUrl: 'my-directive.html',
link: function(scope, element, attrs) {
var inputField = element.find('input');
var name = element.children('#test-name');
scope.width = inputField[0].offsetWidth;
scope.width = inputField[0].offsetWidth /3; // To test
angular.element(name).css('background-color', 'orange');
angular.element(name).css('width', (scope.width + 'px'));
}
};
});
your new template with some CSS removed, and the ID of the test-name set - instead of the name attribute
<script type="text/ng-template" id="my-directive.html">
<div style="width:100%">
<div id="test-name">Hello</div>
<input type="text" style="width:100%;" />
<br /><br />
<div>Width: {{width}}</div>
<div>Error #1: {{err1}}</div>
<div>Error #2: {{err2}}</div>
</div>
</script>