I need to set the width of an HTML element at runtime from my controller in AngularJS. My controller is defined within my directive. I know that I need to set the width of the first ul
element within the directive. Currently, I have the following:
var list = $element.find('ul');
$element(list[0]).css('width', '300px'));
However, when I try this, I get an error that says:
TypeError: object is not a function
What am I doing wrong? How do I set the width of an HTML element at runtime in AngularJS?
Thank you!
I need to set the width of an HTML element at runtime from my controller in AngularJS. My controller is defined within my directive. I know that I need to set the width of the first ul
element within the directive. Currently, I have the following:
var list = $element.find('ul');
$element(list[0]).css('width', '300px'));
However, when I try this, I get an error that says:
TypeError: object is not a function
What am I doing wrong? How do I set the width of an HTML element at runtime in AngularJS?
Thank you!
Share Improve this question asked Oct 8, 2014 at 14:57 user70192user70192 14.3k53 gold badges168 silver badges244 bronze badges 1-
Modifying DOM elements inside a controller isn't a great idea. If you need to do that, use the
link
function. – jessegavin Commented Oct 8, 2014 at 15:08
3 Answers
Reset to default 2You don't need JQuery to do what you want, AngularJS has jqlite. As mentioned in the AngularJS Developer's Guide for directives:
element is the jqLite-wrapped element that this directive matches.
So it should be able to do most of the features that jQuery is capable of, as defined in the angular.element()
documentation.
What the documentation fails to define, is that the jqlite version for finding elements returns an array of HTML elements. So you have to use angular.element()
on each element that you want to manipulate inside that array using the jqlite functionalities. So the code should generally look like this:
DEMO
var list = elem.find('ul');
angular.element(list[0]).css('width', '300px');
You are trying to use $element like its a function.
var list = $element.find('ul');
list[0].css('width', '300px');
or in one line:
$element.find('ul')[0].css('width', '300px');
I would like to add a bit to Brian's answer.
$element. functions differently depending on whether or not jquery is available, because it is a jquery selector. If jquery is available, it will represent a jquery element, if not it will use the jqlite built into angular.
That said, I think the equivalent of your implementation in jquery is something like:
var list = $('ul')
$(list[0]).css('width','300px');
or
$($('ul')[0]).css
Which doesn't look right to me. Brians answer can be converted to jquery succinctly, yours cannot.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745627084a4636874.html
评论列表(0条)