Angular가 있는 여러 컨트롤러한 페이지 앱의 JS
한 페이지 어플리케이션에서 여러 컨트롤러를 사용하는 방법을 알고 싶습니다.나는 그것을 알아내려고 노력했고 나와 매우 유사한 질문들을 발견했지만, 한 페이지 앱에 여러 개의 컨트롤러를 사용하지 않게 되는 특정 문제를 해결하는 수많은 다른 대답들이 있을 뿐이다.
한 페이지에 여러 컨트롤러를 사용하는 것이 현명하지 않기 때문일까요?아니면 그냥 불가능한가?
예를 들어, 이미 메인 페이지에서 작동하는 멋진 이미지 회전식 컨트롤러가 있지만, 그 후에 모달의 사용법(예를 들어)을 배우고, 그것을 위한 새로운 컨트롤러(또는 컨트롤러가 필요한 다른 것)가 필요하다고 합시다.그럼 난 어떻게 하지?
다른 질문에도 나와 거의 비슷한 질문을 하면 사람들은 "*OMG. 왜 그렇게까지 해? 그냥 이렇게 해?.".
가장 좋은 방법 또는 방법은 무엇입니까?
편집
많은 사용자가 2개의 컨트롤러를 선언하고 ng-controller를 사용하여 호출하는 것으로 응답하고 있습니다.아래 코드를 사용하여 MainCtrl을 ng-controller로 호출합니다.
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: "templates/main.html",
controller:'MainCtrl',
})
.otherwise({
template: 'does not exists'
});
});
ng-controller를 사용하지 않고 사용할 수 있는데 왜 여기에 컨트롤러를 설정할 필요가 있습니까?이게 바로 제가 혼란스러워하는 부분입니다.(이렇게 2개의 컨트롤러를 추가할 수는 없습니다...)
뭐가 문제죠?여러 컨트롤러를 사용하려면 여러 ngController 명령을 사용합니다.
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
통상대로 어플리케이션모듈에서 컨트롤러를 사용할 수 있어야 합니다.
가장 기본적인 방법은 다음과 같이 컨트롤러의 기능을 선언하는 것입니다.
function widgetController($scope) {
// stuff here
}
function menuController($scope) {
// stuff here
}
'한 페이지 앱'이라는 의미가 없는 것 같아요.
으로 하나의 것을 , .html을 .1번으로 하다index.htmlNESTED .html 입니다.럼럼왜 왜이 ?이 ?? ???이 방법에서는 표준적인 방법으로 페이지를 로드하지 않고(즉, 페이지 전체를 완전히 새로 고치는 브라우저 호출) Angular/Ajax를 사용하여 컨텐츠 부분을 로드합니다.페이지 변경 간에 깜박임이 나타나지 않기 때문에 페이지에서 이동하지 않은 것처럼 보입니다.그래서 한 페이지에 머무르고 있는 것처럼 느껴집니다.
SINGLE PAGE 앱에는 (예를 들어) 집, 연락처, 포트폴리오, 스토어 등 여러 콘텐츠가 필요합니다.단일 페이지/복수 콘텐츠 앱(각선 방식)은 다음과 같이 구성됩니다.
index.html, : header가 포함되어 .<ng-view>바닥글 " " "contacts.html폼 바닥글 연락처 폼을 표시합니다(헤더 없음, 바닥글 없음).portfolio.html포트폴리오 데이터 삭제(헤더 없음, 바닥글 없음)store.html: 스토어가 포함되어 있으며 머리글도 바닥글도 없습니다.
인덱스에서 "연락처" 메뉴를 클릭하면 어떻게 됩니까?각도가 다음 값을 대체합니다.<ng-view>를 달다contacts.html 표시
좋을까요? 하면 돼요?ngRoute하다 보면 될 거예요.
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl: "templates/index.html",
controller:'MainCtrl',
})
.when('/contacts', {
templateUrl: "templates/contacts.html",
controller:'ContactsCtrl',
})
.otherwise({
template: 'does not exists'
});
});
그러면 올바른 html을 호출하여 올바른 컨트롤러를 전달합니다(루트를 사용하는 경우 디렉티브를 지정하지 마십시오).
contacts.contacts.contacts.controller ng-controller contacts.contacts.controller contacts.controller contacts contacts.controller contacts ng-controller controller이것들은, 의 자컨트롤러가 됩니다.ContactCtrl(본격적으로)의 루트에 는, 「」의 에서는,routeProvider [ Father of view하는 단일 할 수 .
편집 다음 templates/contacts.html을 상상해 보십시오.
<div>
<h3>Contacts</h3>
<p>This is contacts page...</p>
</div>
routeProvider을 나누다html을 사용하다
<div ng-controller="ContactsCtrl">
<h3>Contacts</h3>
<p>This is contacts page...</p>
</div>
다른 컨트롤러를 사용할 수 있다는 것은 다음과 같이 컨트롤러를 내부 DOM 요소에 연결할 수 있음을 의미합니다.
<div>
<h3>Contacts</h3>
<p ng-controller="anotherCtrl">Hello {{name}}! This is contacts page...
</p>
</div>
이것으로 좀 더 명확해졌으면 좋겠다.
A
저는 현재 한 페이지 어플리케이션을 만드는 중입니다.제가 지금까지 가지고 있는 것은 당신의 질문에 대한 답변이라고 생각합니다.베이스 베이스 (base.html)을 .디브ng-view지시하는 것입니다.이 지시문은 새 콘텐츠를 어디에 넣을지 각도로 알려줍니다.저도 angularjs는 처음이라 이게 최선의 방법이라고 말하는 건 아닙니다.
app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home/', {
templateUrl: "templates/home.html",
controller:'homeController',
})
.when('/about/', {
templateUrl: "templates/about.html",
controller: 'aboutController',
})
.otherwise({
template: 'does not exists'
});
});
app.controller('homeController', [
'$scope',
function homeController($scope,) {
$scope.message = 'HOME PAGE';
}
]);
app.controller('aboutController', [
'$scope',
function aboutController($scope) {
$scope.about = 'WE LOVE CODE';
}
]);
base.displaces.displaces(기본값)
<html>
<body>
<div id="sideMenu">
<!-- MENU CONTENT -->
</div>
<div id="content" ng-view="">
<!-- Angular view would show here -->
</div>
<body>
</html>
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
</div>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
///////////////// OR ////////////
<div class="widget" ng-controller="widgetController">
<p>Stuff here</p>
<div class="menu" ng-controller="menuController">
<p>Other stuff here</p>
</div>
</div>
메뉴 컨트롤러는 메뉴 div에 액세스할 수 있습니다.widgetController는 두 가지 모두에 액세스할 수 있습니다.
1개의 모듈에서 복수의 컨트롤러를 선언할 수 있습니다.다음은 예를 제시하겠습니다.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>
<title> New Page </title>
</head>
<body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect -->
<h2> Books </h2>
<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
Enter book name: <input type = "text" ng-model = "book.name"><br>
Enter book category: <input type = "text" ng-model = "book.category"><br>
Enter book price: <input type = "text" ng-model = "book.price"><br>
Enter book author: <input type = "text" ng-model = "book.author"><br>
You are entering book: {{book.bookDetails()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('bookController', function($scope) {
$scope.book = {
name: "",
category: "",
price:"",
author: "",
bookDetails: function() {
var bookObject;
bookObject = $scope.book;
return "Book name: " + bookObject.name + '\n' + "Book category: " + bookObject.category + " \n" + "Book price: " + bookObject.price + " \n" + "Book Author: " + bookObject.author;
}
};
});
</script>
<h2> Albums </h2>
<input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
<div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
Enter Album name: <input type = "text" ng-model = "album.name"><br>
Enter Album category: <input type = "text" ng-model = "album.category"><br>
Enter Album price: <input type = "text" ng-model = "album.price"><br>
Enter Album singer: <input type = "text" ng-model = "album.singer"><br>
You are entering Album: {{album.albumDetails()}}
</div>
<script>
//no need to declare this again ;)
//var mainApp = angular.module("mainApp", []);
mainApp.controller('albumController', function($scope) {
$scope.album = {
name: "",
category: "",
price:"",
singer: "",
albumDetails: function() {
var albumObject;
albumObject = $scope.album;
return "Album name: " + albumObject.name + '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;
}
};
});
</script>
</body>
</html>
앱에 대한 간단한 선언문을 하나 넣었습니다.
var app = angular.module("app", ["xeditable"]);
그 후 서비스 1개와 컨트롤러 2개를 구축했습니다.
각 컨트롤러에 대해 JS에 회선이 있습니다.
app.controller('EditableRowCtrl', function ($scope, CRUD_OperService) {
그리고 HTML에서 앱 스코프를 주변 div로 선언했습니다.
<div ng-app="app">
각 컨트롤러 스코프는 각각 독자적인 주변 div(앱 div 내)로 구분됩니다.
<div ng-controller="EditableRowCtrl">
이것은 잘 작동했다.
템플릿 뷰를 모두 메인html 파일에 포함시킬 수도 있습니다.예:
<body ng-app="testApp">
<h1>Test App</h1>
<div ng-view></div>
<script type = "text/ng-template" id = "index.html">
<h1>Index Page</h1>
<p>{{message}}</p>
</script>
<script type = "text/ng-template" id = "home.html">
<h1>Home Page</h1>
<p>{{message}}</p>
</script>
</body>
이렇게 하면 템플릿마다 다른 컨트롤러가 필요한 경우에도 각도 라우터를 사용할 수 있습니다.http://plnkr.co/edit/9X0fT0Q9MlXtHVVQLhgr?p=preview 의 동작 예에 대해서는, 이 플랭크를 참조해 주세요.
이와 같이 서버에서 클라이언트로 애플리케이션이 전송되면 데이터 요구 등을 할 필요가 없다는 전제 하에 애플리케이션이 완전히 자기 억제됩니다.
언급URL : https://stackoverflow.com/questions/24316355/multiple-controllers-with-angularjs-in-single-page-app
'programing' 카테고리의 다른 글
| jQuery autocomplete with callback ajax json을 사용하여 자동 완성 (0) | 2023.03.19 |
|---|---|
| 부트스트랩에서 스크롤 가능한 열을 만들려면 어떻게 해야 합니까? (0) | 2023.03.19 |
| Woocommerce의 이메일 템플릿을 미리 보는 방법 (0) | 2023.03.19 |
| Mongoose JS를 통한 MongoDB - 검색 기준아이디? (0) | 2023.03.19 |
| 컴파일된 Mongoose 모델은 덮어쓸 수 없습니다. (0) | 2023.03.19 |