AngularJS HTML을 동적으로 추가하고 컨트롤러에 바인드하는 방법
이제 막 각도 맞추기 시작했어JS는 제가 하려는 일에 적합한 아키텍처를 찾는 데 어려움을 겪고 있습니다.1페이지 앱이 있습니다만, URL은 항상 같기 때문에 루트 이외의 루트로 이동할 수 없습니다.내 앱에는 다른 뷰를 호스팅해야 하는 주요 div가 하나 있습니다.새로운 뷰에 액세스 하면 메인 div의 디스플레이를 계승하고 싶다.이 방법으로 로드된 뷰는 일회용 또는 DOM에 숨겨져 있을 수 있습니다.각각의 동작에 관심이 있습니다.
내가 하려는 일의 대략적인 실행 예를 생각해 냈다.이 Plunk의 작업 예를 참조하십시오.기본적으로 HTML을 DOM에 동적으로 로드하여 표준 각도를 갖기를 원합니다.JS컨트롤러는 새로운 HTML에 접속할 수 있습니다.여기 있는 커스텀 디렉티브를 사용하고 $compile()을 사용하여 angular에 접속하는 것보다 더 좋은/심플한 방법이 있을까요?라우터와 같은 것이 있습니다만, 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);
});
}
};
});
감사해요.
앤디
나는 기본 제공 지시어를 사용할 것이다.아래 예에서는 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>
다른 방법도 있다
- 순서 1: sample.disc 파일을 만듭니다.
- 2단계: 일부 id=loadhtml Eg:를 사용하여 div 태그를 만듭니다.
<div id="loadhtml"></div>
순서 3: 모든 컨트롤러에서
var htmlcontent = $('#loadhtml '); htmlcontent.load('/Pages/Common/contact.html') $compile(htmlcontent.contents())($scope);
현재 페이지의 html 페이지를 로드합니다.
저처럼 각도 지령을 사용할 수 없고 각도 범위 밖에서 "고착"된 사람들을 위해, 여기 도움이 될 만한 것이 있습니다.
웹과 각도 문서에서 몇 시간 동안 검색한 후 HTML을 컴파일하여 타깃 내에 배치하고 스코프에 바인드하는 클래스를 만들었습니다($rootScope
없으면$scope
그 요소에 대해서)
/**
* 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 부분은 다음과 같습니다.
.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>
언급URL : https://stackoverflow.com/questions/19845950/angularjs-how-to-dynamically-add-html-and-bind-to-controller
'code' 카테고리의 다른 글
플라스크를 사용하여 오리진 간 자원 공유 해결 (0) | 2023.03.09 |
---|---|
ReactJ에서는 동기 호출 시 setState가 다르게 동작하는 이유는 무엇입니까? (0) | 2023.03.04 |
스프링 테스트 및 보안:인증을 모의하는 방법 (0) | 2023.03.04 |
Mongo에서는 샤딩과 복제의 차이점은 무엇입니까? (0) | 2023.03.04 |
jq를 사용하여 이중 따옴표를 사용하지 않는 JSON의 Concat 번호 (0) | 2023.03.04 |