在通过指令加载的模板中初始化控制器?

时间:2014-06-30 19:02:57

标签: angularjs

获得回复

<section ng-controller="BookingController"></section>

指令

MyApp.directive "loadThing", ($rootScope, $compile) ->
    return {
        restrict: "AE",
        link: (scope, element, attrs) ->
            $.get BASE_URL + '/load/template/' + attrs.loadThing, (response) ->
                element.html(response)
                $compile(element)
    }

我正在使用ajax加载模板,该模板中已声明了ng-controller,但控制器未被初始化。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

链接通常用于基于事件的行为,我不确定您为什么要使用Ajax,但您可能会尝试在控制器中声明控制器和模板。它看起来像这样:

MyApp.directive('loadThing', function($rootScope, $compile) {
    return {
         restrict: "AE",
         templateUrl: 'yourPathHere.js',
         controller: 'MyController'
    }
});

答案 1 :(得分:0)

叹息,这是一个愚蠢的错误。

需要:

template = $(response)
$compile(template)(scope)
element.append(template)

密钥漏洞没有调用函数$ compile返回。

相关问题