刚开始接触Angular对Angular不是很熟悉。做界面插入新的html界面的时候遇到了一些问题。刚开始想着使用iframe,但是使用iframe的时候遇到了一些问题包括不能访问父级的angular事件,于是改为使用:ng-bind-html
html:
<div id="htmldiv" ng-bind-html="htmlstr">
</div>
js:
app.controller('Contract',
[
'$scope', '$rootScope', '$http', '$state', '$stateParams', '$timeout', '$filter', 'systemUrlBase', 'systemRequestBase', 'Excel', 'viewData', 'systemRequestService', '$sce', '$compile',
function ($scope, $rootScope, $http, $state, $stateParams, $timeout, $filter, systemUrlBase, systemRequestBase, Excel, viewData, systemRequestService, $sce, $compile) {
angular.extend($scope, viewData);
$scope.htmlstr = $sce.trustAsHtml(viewData.viewModel);//注意$sce
}
]);
注意$sce。
结果是和iframe的效果类似:页面没问题,依旧不能访问到angular事件。因为angular插入html时需要compile一下。
于是最后改为:
<div id="htmldiv">
</div>
app.controller('Contract',
[
'$scope', '$rootScope', '$http', '$state', '$stateParams', '$timeout', '$filter', 'systemUrlBase', 'systemRequestBase', 'Excel', 'viewData', 'systemRequestService', '$sce', '$compile',
function ($scope, $rootScope, $http, $state, $stateParams, $timeout, $filter, systemUrlBase, systemRequestBase, Excel, viewData, systemRequestService, $sce, $compile) {
angular.extend($scope, viewData);
var compileFn = $compile(viewData.viewModel);
//$scope.htmlstr = $sce.trustAsHtml(viewData.viewModel);
var $dom = compileFn($scope);
$dom.appendTo(document.getElementById('htmldiv'));
}
]);
这样就能访问到父级定义的Angular事件了。
总结:问题其实不难,重要的是多多实践,对一些东西还是不熟练,遇到问题解决问题,积攒一些经验。