我想在指令的模板函数中使用 $scope 变量,如下所示。 换句话说,我想在指令内部并使用 $scope 变量生成指令模板。
帮我将模板函数连接到 Controller 。
directive("data", ['$compile', '$http', '$templateCache',function ($http,$rootScope) {
return{
link: function (scope, elem, attrs, ctrl) {
scope.template = something // I want Generate template here
},
template:function(element , attrs){
return $scope.template // I can't access scope here
}
}
最佳答案
您无法访问模板函数中的范围,如果您想以某种方式生成模板,然后在指令内渲染模板,我建议使用 $compile service在链接函数中以这种方式:
var a = angular.module('myApp', []);
a.controller('ctrl', function ($scope) {
$scope.myTemplate = '<span class="custom-tpl"> my template </span>';
});
a.directive('dynamicTemplate', [ '$compile',
function ($compile) {
'use strict';
return {
restrict: 'A',
scope: {
customTemplate: '='
},
link: function ($scope, $element, $attrs, $controller) {
var compiledTemplate = $compile($scope.customTemplate)($scope);
$element.html('').append(compiledTemplate);
}
};
}]);
你可以看看here
关于angularjs - 如何在指令模板中使用范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25341641/