我有一个指令,它有一个模板函数
restrict: 'E', // 'A' is the default, so you could remove this line
scope: {
field : '@field',
},
template: function( element, attrs) {
//some code here
},
link: function (scope, element, attrs) {
是否可以从模板函数访问指令的范围?我正在尝试做类似的事情
if (scope.columnType == 'test'){ .. }
因为我想根据其他值渲染不同的模板
最佳答案
您可以从 Link 函数访问指令 $scope,$编译任何 HTML 并将其附加到指令元素(实际上,它可以被初始化为空):
angular.module("example")
.directive('example', function($compile) {
return {
restrict: 'E',
link: function(scope, element, attrs){
scope.nums = [1, 2, 3];
var html = '<div ng-model="scope"><p ng-repeat="n in nums">{{ n }}</p></div>';
var el = $compile(html)(scope);
element.append(el);
}
}
});
请注意,我必须明确指定标签的数据模型 (ng-model = "scope")。否则我无法让它工作。
关于javascript - 来自指令模板函数的 Angular 访问范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30704757/