0

So I have some html that gets loaded into the #panel div dynamically depending on which questionNumber the user is on. This is not all of the code but all of the relevant code I think. Anyway, the <input> get's loaded into the page but it doesn't actually do anything. what am I missing here? I have the same problem when the questionNumber === 1, where the binded variables just show up as {{variable}} etc

var readingController = function (scope, Romanize){
        scope.usersRomanization;
        //alert(scope.usersRomanization);
}

var app = angular.module('Tutorials', ['functions', 'tutorials']).controller('getAnswers', function ($scope, $element, Position, Romanize) {
$scope.sectionNumber = Position.sectionNumber;
if ($scope.sectionNumber === 0){
    $('#panel').html('<div ng-controller="readingController"><input ng-model="usersRomanization"></input></div>');
    readingController($scope, Romanize);
}

<body ng-controller="getAnswers">
    <div  id="panel">
    </div>
</body>
Tules
  • 4,905
  • 2
  • 27
  • 29
  • You can't have jQuery in your controllers. See [How do I “think in AngularJS” if I have a jQuery background?](http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background). – Stewie Mar 15 '13 at 17:06
  • Then how else should I load this html into the page based on questionNumber? Despite the fact it's against conventions shouldn't this still technically work? – Tules Mar 15 '13 at 17:16

1 Answers1

1

If you add HTML to the DOM, you have to tell Angular to $compile it. This should be done in a directive. You'll need to inject $compile then do something like this:

var content = '<div ng-controller=...></div>';
var compiled = $compile(content)(scope);
// then put the content where you want

Or better, define a directive and use a template, which will automatically get compiled for you by Angular.

Other alternatives are ng-include (which will compile the loaded content for you) and ng-switch, which would allow you to put the templates into the HTML.

Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • ok then in that case how do I dynamically load the directive based on questionNumber? – Tules Mar 15 '13 at 17:36
  • Try ng-include or ng-switch. It is hard to say without knowing how many questions you have, or where your templates are coming from -- are your templates in separate files or can you use (script)[http://docs.angularjs.org/api/ng.directive:script] to put them into your Javascript? If so, use ng-include. With ng-switch you can put all your templates into your HTML. – Mark Rajcok Mar 15 '13 at 17:44
  • sorry I should have said based on sectionNumber, at the moment there are only 2 sections but there will be more in future – Tules Mar 15 '13 at 17:49
  • looks like ng-switch is exactly what I'm looking for, I will just include the html in the document body :) – Tules Mar 15 '13 at 17:56