$scope 不适用于指令中的已编译模板
$scope doesn't apply to compiled template in directive
对于具有多个模板的弹出窗口,我有以下指令:
app.directive('popup', function ($http, $rootScope, $templateCache, $compile, $parse, Popup) {
return {
link: function ($scope, $element, $attrs) {
$element.bind('click', function () {
var data = {
index: $attrs.index
}
$http.get('/partial/' + $attrs.popup + '.html', {cache: $templateCache}).success(function (tplContent) {
var mainElement = angular.element(document.getElementById('main'));
mainElement.append($compile(tplContent)($scope));
Popup.show(data);
});
});
}
}
});
我已将 visibility
标志固定到 $rootScope
(以使 css 可见弹出窗口)以及数据对象中的索引和项目。弹出模板如下所示:
<section class="popup" ng-class="{'show': popup.visibility}">
<h1>{{data[popup.index].title}}<h1>
<p>{{data[popup.index].message}}<p>
</section>
该指令加载弹出模板并将其附加到我的 mainElement
,但不应用范围。因此不会出现弹出窗口,也不会绑定任何数据。
您需要通过 $scope.$parent 而不是 $scope 进行编译。因为你在子 $scope 中。
对于具有多个模板的弹出窗口,我有以下指令:
app.directive('popup', function ($http, $rootScope, $templateCache, $compile, $parse, Popup) {
return {
link: function ($scope, $element, $attrs) {
$element.bind('click', function () {
var data = {
index: $attrs.index
}
$http.get('/partial/' + $attrs.popup + '.html', {cache: $templateCache}).success(function (tplContent) {
var mainElement = angular.element(document.getElementById('main'));
mainElement.append($compile(tplContent)($scope));
Popup.show(data);
});
});
}
}
});
我已将 visibility
标志固定到 $rootScope
(以使 css 可见弹出窗口)以及数据对象中的索引和项目。弹出模板如下所示:
<section class="popup" ng-class="{'show': popup.visibility}">
<h1>{{data[popup.index].title}}<h1>
<p>{{data[popup.index].message}}<p>
</section>
该指令加载弹出模板并将其附加到我的 mainElement
,但不应用范围。因此不会出现弹出窗口,也不会绑定任何数据。
您需要通过 $scope.$parent 而不是 $scope 进行编译。因为你在子 $scope 中。