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.
testDiv.css('width', (scope.width + 'px'));
andtestDiv.css('width', '500px');
– PSL Oct 9 '14 at 15:45