感谢您的浏览。我将直接深入:
JSON 对象具有带有 ng-click
的 HTML 链接属性,采用ng-bind-html
,与 $sce
的trustAsHtml
确保 HTML 安全。我也用过自定义angular-compile
在 $q
中加载 json 后,将 Angular 点击监听器编译到应用程序中的指令 promise 。
乍一看,所有这些都按预期工作......
JSON
{
"text" : "Sample of text with <a data-ng-click=\"__services._animation.openModal('g');\">modal trigger</a>?"
}
查看
<p data-ng-bind-html="__services.trustAsHTML(__data.steps[step.text])"
data-angular-compile></p>
指令
angular.module('app.directives.AngularCompile', [], ["$compileProvider", function($compileProvider) {
$compileProvider.directive('angularCompile', ["$compile", function($compile) {
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
return scope.$eval(attrs.angularCompile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
);
};
}])
}]);
问题:
好的,这样就可以了。我的应用程序加载,它提供安全的 HTML,而我的 ng-click
打开模式,传递它的参数。我明白了class='ng-binding'
关于周边p
标签,class="ng-scope"
关于a
生成的 html 中的标记。万岁!
下一个业务顺序是将这些数据写入另一个跟踪进度的模型中,并通过相同的 ng-bind
运行它。 , trustAsHTML
, angular-compile treatment
从另一个 Angular 来看。只需将数据复制到同级对象中即可。
这就是失败的地方!
<p data-ng-bind-html="__services.trustAsHTML(__state.modal.text)"
data-angular-compile></p>
在第二个 View 中,这是同一页面上相同范围($rootScope)中的模式 - 绑定(bind),并且应用了 trustAsHTML Angular。但链接无法点击,也没有class="ng-scope"
生成于 a
标签。
如果对我的设置的进一步解释可能有助于理解该问题,请让我在这里详细说明。所有初始应用程序均由礼宾人员设置,并将大部分数据存储在 $rootScope 中:
return angular
.module('app', [
'ngResource',
'ngSanitize',
'ui.router',
'oslerApp.controllers.GuideController',
'oslerApp.services.ConciergeService',
'oslerApp.services.DataService',
'oslerApp.services.LocationService',
'oslerApp.services.StatesService',
'oslerApp.directives.AngularCompile',
])
.config(function($stateProvider, $urlRouterProvider) {
// For any unmatched url, redirect to landing
$urlRouterProvider.otherwise("/");
// Now set up the states
$stateProvider
.state('guide', {
url: "/guide",
templateUrl: "views/guide.html",
controller: 'GuideController as guide'
})
.state('contact', {
url: "/contact",
templateUrl: "views/contact.html"
})
})
.run(function(ConciergeService) {
ConciergeService.init();
});
我花了 2 天重构我的整个网站,看看是否是因为模式位于它自己的指令中,但将其放在相同的模板和范围内似乎对我没有帮助。
最佳答案
教训:如果您必须重构所有内容但仍然没有取得任何进展,那么您就做错了。
为了解决这个问题,经过两天的拉扯,我做了一个小小的服务,并通过它传递了问题文本:
compiler: function(element, template, content, scope) {
element = $(element);
template = template[0] + content + template[1];
var linkFn = $compile(template);
content = linkFn(scope);
element.replaceWith(content);
},
关于javascript - 自定义 $compile 指令仅有时适用于同一范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552608/