我有一个用于显示模态窗口的角度指令。它可以接受HTML标记之间内联的内容,也可以指向模板。使用此指令时,当我使用此指令的转换内联版本时,我似乎可以正常访问$scope
,但是当我使用模板时,我没有。
我在这里缺少什么?我制作了一个具有相同行为的较小样本指令。
演示: http://fiddle.jshell.net/ahezfaxj/2
内联内容使用
<ang-test show="showBoolean">
<p>Content here!</p>
</ang-test>
模板用法
<ang-test show="showBoolean" template="'myTemplate.html'"></ang-test>
指令
app.directive("angTest", function () {
return {
template: function () {
return "<div class='test-container'>" +
" <div ng-if='show && template' ng-include='template'></div>" +
" <div ng-if='show && !template' ng-transclude></div>" +
"</div>";
},
restrict: "E",
replace: true,
transclude: true,
scope: {
template: "@",
show: "="
},
link: function ($scope, $element, attrs) {
if(value){
$element[0].style.display="block";
}else{
$element[0].style.display="none";
}
}
};
});
答案 0 :(得分:0)
请参阅下面的演示。您在指令中创建了隔离范围,因此您的指令范围与控制器$范围不同。但是你也可以在你的指令范围中添加 thing ,如下例所示。
我希望这会有所帮助。
var app = angular.module("app", []);
app.controller("BaseCtrl", function ($scope) {
$scope.thing = "Hello!";
$scope.showOne=false;
$scope.showTwo=false;
});
app.directive("angTest", function () {
return {
template: function () {
return "<div class='test-container'>" +
" <div ng-if='show && template' ng-include='template'></div>" +
" <div ng-if='show && !template' ng-transclude></div>" +
"</div>";
},
restrict: "E",
replace: true,
transclude: true,
scope: {
template: "@",
show: "=",
thing:'@'
},
link: function ($scope, $element, attrs) {
//Show/hide when `show` changes
$scope.$watch("show", function (value) {
if(value){
$element[0].style.display="block";
}else{
$element[0].style.display="none";
}
});
}
};
});
&#13;
.test-container{
padding:5px;
background: #EEE;
}
.transcluded {
color:red
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="BaseCtrl">
Outside Directive: <strong>{{thing}}</strong>
<hr />
<button type="button" ng-click="showOne=!showOne">Toggle One</button>
<ang-test show="showOne">
<p class="transcluded">Inside Included Directive: <strong>--> thing transcluded-->{{thing}}</strong></p>
</ang-test>
<hr />
<script type="text/ng-template" id="myTemplate">
<p>Inside Template Directive: <strong>thing from directive scope -->{{thing}}</strong></p>
</script>
<button type="button" ng-click="showTwo=!showTwo" >Toggle Two</button>
<ang-test show="showTwo" template="myTemplate" thing="{{thing}}"></ang-test>
</div>
</div>
&#13;