1

I have a table row that I can dynamically add into an existing table using some jQuery like so:

$("#add-item").click(function(){
    var itemRow = "<tr><td><span contenteditable='true'><a href='#'>Edit me<a/></span></td></tr>";
    $("#job-table").hide(0).append(itemRow).fadeIn(500);
});

I also have some data-binding that I can do with Angular like so:

<div>
    <input type="text" ng-model="data.message">
    <h1>{{data.message}}</h1>
</div>

What I want is to have something like this:

$("#add-item").click(function(){
    var itemRow = "<tr><td><span contenteditable='true'><a href='http://something.com/{{content.url}}'>content.url<a/></span></td></tr>";
    $("#job-table").hide(0).append(itemRow).fadeIn(500);
});

The problem is that angular can't access this dynamically loaded element because it's not available at load time.

What would be the best way to achieve this?

1
  • On a side note, you should be using directives for DOM manipulation. Commented Oct 21, 2013 at 18:18

1 Answer 1

5

The best way to achieve this is to forget everything you know about jQuery. Put an "items" array in your scope and use an ng-repeat.

psuedocode:

<tr ng-repeat = "item in items">
<td><span contenteditable='true'><a ng-href='http://something.com/{{item.url}}'>item.url<a/></span></td>
</tr>

Now use ng-click to trigger adding an item to the items array and you're good to go. No jQuery required. It can even be as simple as <button ng-click="items.push({url:'what'})">add</button> and it will automatically appear.

Here's a fiddle: http://jsfiddle.net/VEbsU/1/ showing a full example

Sign up to request clarification or add additional context in comments.

1 Comment

Great example and explanation.

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.