如何将指令控制器中定义的范围变量解析为要在 angular js 中的指令模板中使用的另一个指令
How to resolve a scope variable defined in directive controller as another directive to be used within directive template in angular js
这是我正在尝试做的事情:
(function () {
'use strict';
var sampleApp = angular.module('sample');
sampleApp.directive('myDirective', sampleAppDirective);
function sampleAppDirective () {
sampleAppDirectiveController.$inject = ['$scope', '$http', '$attrs', '$element', '$compile', '$log'];
return {
restrict : 'EA',
controller : sampleAppDirectiveController,
templateUrl : 'partials/sample.html'
};
function sampleAppDirectiveController ($scope, $http, $attrs, $element, $compile, $log) {
$scope.placeholderDir = 'my-other-directive';
}
}})();
partials/sample.html 中的模板如下所示
<div><div {{placeholderDir}}></div></div>
是否可以在 myDirective 控制器中将模板解析成这样的东西
<div><div my-other-directive></div></div>
我想确保我的其他指令在呈现时也解析为它的模板。
请帮忙!
是的,但您需要查看 $compile 服务。
基本上,您需要在指令中生成标记并使用 $compile 服务对其进行编译。
您可以在 link 函数中执行类似的操作:
link: function($scope, $element) {
$compile($element.contents())($scope);
}
虽然没有测试。
您也可以从 DDO 中丢弃 templateUrl 并直接在您的元素中插入您的标记:
link: function($scope, $element) {
$element.html('<div><div ' + $scope.placeholderDir + '></div></div>');
$compile($element.contents())($scope);
}
这是我正在尝试做的事情:
(function () {
'use strict';
var sampleApp = angular.module('sample');
sampleApp.directive('myDirective', sampleAppDirective);
function sampleAppDirective () {
sampleAppDirectiveController.$inject = ['$scope', '$http', '$attrs', '$element', '$compile', '$log'];
return {
restrict : 'EA',
controller : sampleAppDirectiveController,
templateUrl : 'partials/sample.html'
};
function sampleAppDirectiveController ($scope, $http, $attrs, $element, $compile, $log) {
$scope.placeholderDir = 'my-other-directive';
}
}})();
partials/sample.html 中的模板如下所示
<div><div {{placeholderDir}}></div></div>
是否可以在 myDirective 控制器中将模板解析成这样的东西
<div><div my-other-directive></div></div>
我想确保我的其他指令在呈现时也解析为它的模板。
请帮忙!
是的,但您需要查看 $compile 服务。
基本上,您需要在指令中生成标记并使用 $compile 服务对其进行编译。
您可以在 link 函数中执行类似的操作:
link: function($scope, $element) {
$compile($element.contents())($scope);
}
虽然没有测试。
您也可以从 DDO 中丢弃 templateUrl 并直接在您的元素中插入您的标记:
link: function($scope, $element) {
$element.html('<div><div ' + $scope.placeholderDir + '></div></div>');
$compile($element.contents())($scope);
}