Send value as argument to a dynamically assigned controller

62 Views Asked by At

I'm trying to reproduce the modal view of AngularUI and dialog view of angular material behavior of assigning a controller dynamically and be able to send values as arguments

I tried to mimic AngularUI code without success:

var elem =  document.getElementById('placeholder');
elem.setAttribute('ng-controller', 'ctrl');

var injector = angular.element(elem).injector();
var compile = injector.get('$compile');
var rootScope = injector.get('$rootScope');
var controller = injector.get('$controller');
var ctrlInstance = controller('ctrl', {$scope:rootScope, value:'hello'}); 
var result = compile(elem)(rootScope);

It works for dynamically assigning the controller without passing the value. What am I doing wrong?

http://codepen.io/anon/pen/oXKvyb

1

There are 1 best solutions below

2
On

Don't set the controller on the element. : http://codepen.io/anon/pen/MwNgZx?editors=101

Updated method:

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

    eSelect.setAttribute('ng-options', 'o as o for o in rows');
    eSelect.setAttribute('ng-model', 'selectedValue');

    var injector = angular.element(elem).injector();
    var compile = injector.get('$compile');
    var rootScope = injector.get('$rootScope');
    var controller = injector.get('$controller');
  var result = compile(elem)(rootScope);  
  var ctrlInstance = controller('ctrl', {$scope:rootScope, value:'hello'});

}

Also, when getting the select you were doing children[1].children[0] and that was not correct.

I'm guessing that if you set the ng-controller on the element, angular also tries to instantiate it but doesn't know where to get the value parameter.

Edit

And I made the example do what you wanted it to do .. I think :)