[英]AngularJS How to dynamically add HTML and bind to controller
我剛開始使用angularJS並且正在努力找出適合我正在嘗試的架構。 我有一個單頁應用程序,但URL始終保持不變 ; 我不希望用戶能夠導航到root之外的任何路由。 在我的應用程序中,有一個主要div需要托管不同的視圖。 訪問新視圖時,我希望它接管主div中的顯示。 以這種方式加載的視圖可以丟棄或隱藏在DOM中 - 我很想知道每個視圖的工作原理。
我想出了一個粗略的工作示例,說明我正在嘗試做什么。 請參閱此Plunk中的工作示例。 基本上我想動態地將HTML加載到DOM中,並讓標准的angularJS控制器能夠掛鈎到新的HTML中。 有沒有更好/更簡單的方法來做到這一點,而不是使用我在這里的自定義指令並使用$ compile()來連接到角度? 也許有點像路由器,但是不需要URL有變化才能運行?
這是我到目前為止使用的特殊指令(取自另一個SO帖子):
// Stolen from: http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database
myApp.directive('dynamic', function ($compile) {
return {
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
if (!html) {
return;
}
ele.html((typeof(html) === 'string') ? html : html.data);
$compile(ele.contents())(scope);
});
}
};
});
謝謝,
安迪
我會使用內置的ngInclude
指令。 在下面的示例中,您甚至不需要編寫任何javascript。 模板可以輕松地存在於遠程URL中。
這是一個有效的演示: http : //plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p = preview
<p>Select page content template via dropdown</p>
<select ng-model="template">
<option value="page1">Page 1</option>
<option value="page2">Page 2</option>
</select>
<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>
<ng-include src="template"></ng-include>
<script type="text/ng-template" id="page1">
<h1 style="color: blue;">This is the page 1 content</h1>
</script>
<script type="text/ng-template" id="page2">
<h1 style="color:green;">This is the page 2 content</h1>
</script>
還有另一種方式
<div id="loadhtml"></div>
第3步:在任何控制器中
var htmlcontent = $('#loadhtml '); htmlcontent.load('/Pages/Common/contact.html') $compile(htmlcontent.contents())($scope);
這將在當前頁面中加載html頁面
對於那些像我一樣,沒有可能使用角度指令並被“卡住”在角度范圍之外的人,這里可能會對你有所幫助。
在網上和角度文檔上搜索了幾個小時后,我創建了一個編譯HTML的類,將其放在目標中,並將其綁定到范圍(如果該元素沒有$scope
, $rootScope
)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
它涵蓋了我的所有案例,但是如果你發現我應該添加的內容,請隨意評論或編輯。
希望它會有所幫助。
看看這個例子是否提供了任何說明。 基本上,您配置一組路由並包含基於路由的部分模板。 在主index.html中設置ng-view允許您注入這些部分視圖。
配置部分如下所示:
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/', {controller:'ListCtrl', templateUrl:'list.html'})
.otherwise({redirectTo:'/'});
}])
將部分視圖注入主模板的入口點是:
<div class="container" ng-view=""></div>
我需要在加載幾個模板后執行一個指令,所以我創建了這個指令:
utilModule.directive('utPreload', ['$templateRequest', '$templateCache', '$q', '$compile', '$rootScope', function($templateRequest, $templateCache, $q, $compile, $rootScope) { 'use strict'; var link = function(scope, element) { scope.$watch('done', function(done) { if(done === true) { var html = ""; if(scope.slvAppend === true) { scope.urls.forEach(function(url) { html += $templateCache.get(url); }); } html += scope.slvHtml; element.append($compile(html)($rootScope)); } }); }; var controller = function($scope) { $scope.done = false; $scope.html = ""; $scope.urls = $scope.slvTemplate.split(','); var promises = []; $scope.urls.forEach(function(url) { promises.add($templateRequest(url)); }); $q.all(promises).then( function() { // SUCCESS $scope.done = true; }, function() { // FAIL throw new Error('preload failed.'); } ); }; return { restrict: 'A', scope: { utTemplate: '=', // the templates to load (comma separated) utAppend: '=', // boolean: append templates to DOM after load? utHtml: '=' // the html to append and compile after templates have been loaded }, link: link, controller: controller }; }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script> <div class="container-fluid" ut-preload ut-append="true" ut-template="'html/one.html,html/two.html'" ut-html="'<my-directive></my-directive>'"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.