Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS and generated elements

Tags:

angularjs

We have some third party javascript components that are generating some html elements. I'd like to couple it with AngularJS.

I've tried this code

<div ng-controller="ExpensesCtrl">
    <form id="expensesform">
        <input type="text" ng-model="expense.name" />
        <input type="text" ng-model="expense.amount" />
    </form>
    <button ng-click="add()">Add</button>expense | json
</div>

function ExpensesCtrl($scope) {

    $scope.expense = {};
    $scope.add = function () {
        $("#expensesform").append("<input type='text' ng-model='expense.age' />");
    };
}

http://jsfiddle.net/tChNh/

but it doesn't work like excepted.

Is there any chance to get this working ?

like image 903
user49126 Avatar asked Jun 01 '12 20:06

user49126


1 Answers

This is the wrong way to do it, but for this particular scenario you'd want to do something like this: http://jsfiddle.net/wXZL7/1. Inject the $compile service.

Again, this isn't the right way to do it with Angular. Angular's thing is 'You don't have to mess with the DOM in your controller, let the HTML and directives do that'.

You want to create a directive to wrap whatever is generating your elements and let that do it. Read the directives guide for examples: http://docs.angularjs.org/guide/directive

like image 146
Andrew Joslin Avatar answered Nov 03 '22 00:11

Andrew Joslin