我想在这样的指令的模板函数中使用 $scope 变量。
换句话说,我想在指令内部并使用 $scope 变量生成指令模板。
帮助我将模板功能连接到控制器。
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
}
}
您无法访问模板函数中的范围,如果您想以某种方式生成模板,然后在指令内渲染模板,我建议使用$编译服务 https://docs.angularjs.org/api/ng/service/%24compile在链接函数内部以这种方式:
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 http://jsfiddle.net/JaimeBeneytez/3d791ya6/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)