Assign controller to element dynamically after bootstrap

2.9k views Asked by At

I have an AngularJS app that I manually bootstrap at time 't'. At time 't + 1', I would like to show an HTML element that has no ng-controller attached. I would like to dynamically add a ng-controller to this element so it can communicate with my javascript code.

How can I do that?

PS I tried to dynamically add the ng-controller attribute to the element but it doesn't work.

2

There are 2 answers

2
Skarllot On BEST ANSWER

To do that you need to compile elements.

HTML

<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.5/angular.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

    <link href="main.css" rel="stylesheet" type="text/css" />
    <script src="main.js"></script>
<meta charset=utf-8 />
<title>Angular JS</title>
</head>
<body ng-controller="parentCtrl">
    <button ng-click="setCtrl2()">Set Controller</button>
    <div id="placeholder">
        <span></span>
        <select>
            <option></option>
        </select>
        <span class="input-append">
            <input id="add" type="text" placeholder="Another one ?" ng-model="addName" />
            <input type="submit" class="btn btn-primary" ng-click="addRow()" value="+ add" />
        </span>
    </div>
</body>
</html>

Javascript

angular.module('app', []);

angular.module('app').controller('ctrl', function($scope) {
      $scope.rows = ['Paul','John','Lucie'];
        $scope.name = 'Jack';

      $scope.addRow = function(){
        $scope.rows.push($scope.addName);
        $scope.addName = "";
          console.log($scope.rows);
      };
})
.controller('parentCtrl', function($scope) {
    $scope.setCtrl2 = setCtrl;
});

function setCtrl() {
    var elem =  document.getElementById('placeholder');
    elem.setAttribute('ng-controller', 'ctrl');
    var eSpan = elem.children[0];
    var eSelect = elem.children[1].children[0];
    eSpan.setAttribute('ng-bind', 'name');
    eSelect.setAttribute('ng-repeat', 'row in rows');
    eSelect.setAttribute('value', '{{ row }}');
    eSelect.setAttribute('ng-bind', 'row');

    var injector = angular.element(elem).injector();
    var compile = injector.get('$compile');
    var rootScope = injector.get('$rootScope');
    var result = compile(elem)(rootScope);
    // When outside of AngularJS you need to call digest
    // rootScope.$digest();
}

See: http://codepen.io/skarllot/pen/LVKpgd

0
Miles Grimes On

You don't mention whether you've looked at previously asked questions. I found two which look like they could address the question you've asked:

Loading an AngularJS controller dynamically

How to bind an AngularJS controller to dynamically added HTML?