【问题标题】:AngularJS - how do you associate a controller by path after compiling the html?AngularJS - 编译 html 后如何通过路径关联控制器?
【发布时间】:2016-05-27 16:35:04
【问题描述】:

从模板编译后,是否可以动态关联控制器?

//Controller /path/ctrl/MainCtrl.js
angular.module('app')
    .controller('MainCtrl', function () {

    });

//Directive  /path/dir/myDir.js
function link(scope, element, attrs) {
    $templateRequest('path/oneTpl.tpl').then(function (html) {
        $compile(element.html(html).contents())(scope);
        //How can I do to dynamically inject MainCtrl into the oneTpl.tpl template using the path (/path/ctrl/MainCtrl.js)?
    });
}

【问题讨论】:

    标签: javascript angularjs angularjs-directive angular-template angular-controller


    【解决方案1】:

    您可以尝试向已编译的模板添加属性(很高兴知道您的模板到底是什么)。

    试试下面的代码:

    element.setAttribute(name, value);
    

    例子:

    <button>Hello World</button>
    var b = document.querySelector("button"); 
    
    b.setAttribute("disabled", "disabled");
    

    所以您只需要模板的标识符,例如id 或 class 然后设置你的属性。

    jQuery:$('#yourTemplate').setAttribute('ng-controller','yourController' );

    如果这对您没有帮助,也许以下主题会对您有所帮助:

    AngularJS: dynamically assign controller from ng-repeat

    Dynamic NG-Controller Name

    Dynamically assign ng-controller on runtime

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多