将值作为参数发送到动态分配的控制器

时间:2015-08-23 03:46:41

标签: javascript angularjs ng-controller

我试图重现AngularUI的模态视图和angular material动态分配控制器的行为的对话视图,并能够将值作为参数发送

我试图模仿AngularUI代码但没有成功:

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);

它适用于动态分配控制器而不传递值。我做错了什么?

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

1 个答案:

答案 0 :(得分:1)

不要在元素上设置控制器。 : http://codepen.io/anon/pen/MwNgZx?editors=101

更新方法:

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'});

}

此外,在获得选择时,你正在做孩子[1]。儿童[0],这是不正确的。

我猜测如果你在元素上设置ng-controller,angular也会尝试实例化它,但不知道从哪里获取value参数。

修改

我让这个例子做你想做的事情......我想:)