1

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!

1
  • Modifying DOM elements inside a controller isn't a great idea. If you need to do that, use the link function. Commented Oct 8, 2014 at 15:08

3 Answers 3

2

You 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');
Sign up to request clarification or add additional context in comments.

Comments

1

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');

2 Comments

Oddly, when I try that I get an error that says TypeError: Cannot read property 'css' of undefined. If I do a console.log($element.find('ul')[0]); I see [ready: function, toString: function, eq: function, push: function, sort: function… in the console window.
You need to add the full jquery library to use all jquery functions.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.