访问 angular 指令模板中的隔离范围
Access isolated scope in angular directive template
我目前正在编写一个 angular 指令,该指令使用另一个 HTML 文件中的模板和一个独立的模板。该指令通过 @ 将一些字符串获取到其范围,并且该值在控制器函数中可用。
不知何故,它无法通过 HTML 模板中的 {{}} 获得。为什么?我该如何改变它?我阅读了一些有关使用父范围的模板的内容,但我并不完全理解。
这是一个代码示例:
angular.module('moduleName')
.directive('aGreatDirective', function () {
return {
restrict: 'E',
scope: {
mapid: '@'
},
templateUrl: "path/to/template.html",
controller: ['$scope', function (scope) {
console.log($scope.mapid); // is defined
}
}
});
以及模板的 html 代码:
<div id="{{mapid}}"></div>
浏览器中的结果与应有的完全相同:
<div id="theValueOfmapid"></div>
感谢您的帮助!
PS 这是一个 jsfiddle:fiddle
您的 fiddle 不正确,因为您没有正确定义控制器或正确注入 $scope。以下将正常工作:
模板:
<div ng-controller="MyCtrl">
<a-great-directive mapid="thisisthemapid"></a-great-directive>
Some other code
</div>
js:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function () {
});
myApp.directive('aGreatDirective', function() {
return {
restrict: 'E',
scope: {
mapid: '@'
},
template: "<div id='{{mapid}}'> {{mapid}} </div>",
controller: ['$scope', function($scope) {
console.log($scope.mapid); // is defined
}
]}
});
请注意,在我的示例中,出于一致性原因,指令控制器中的注入变量应该是 $scope
,而不是 scope
。
我目前正在编写一个 angular 指令,该指令使用另一个 HTML 文件中的模板和一个独立的模板。该指令通过 @ 将一些字符串获取到其范围,并且该值在控制器函数中可用。 不知何故,它无法通过 HTML 模板中的 {{}} 获得。为什么?我该如何改变它?我阅读了一些有关使用父范围的模板的内容,但我并不完全理解。
这是一个代码示例:
angular.module('moduleName')
.directive('aGreatDirective', function () {
return {
restrict: 'E',
scope: {
mapid: '@'
},
templateUrl: "path/to/template.html",
controller: ['$scope', function (scope) {
console.log($scope.mapid); // is defined
}
}
});
以及模板的 html 代码:
<div id="{{mapid}}"></div>
浏览器中的结果与应有的完全相同:
<div id="theValueOfmapid"></div>
感谢您的帮助!
PS 这是一个 jsfiddle:fiddle
您的 fiddle 不正确,因为您没有正确定义控制器或正确注入 $scope。以下将正常工作:
模板:
<div ng-controller="MyCtrl">
<a-great-directive mapid="thisisthemapid"></a-great-directive>
Some other code
</div>
js:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function () {
});
myApp.directive('aGreatDirective', function() {
return {
restrict: 'E',
scope: {
mapid: '@'
},
template: "<div id='{{mapid}}'> {{mapid}} </div>",
controller: ['$scope', function($scope) {
console.log($scope.mapid); // is defined
}
]}
});
请注意,在我的示例中,出于一致性原因,指令控制器中的注入变量应该是 $scope
,而不是 scope
。