gpt4 book ai didi

angularjs - 我可以在 AngularJS 的模板文件中保留 Controller 吗?

转载 作者:行者123 更新时间:2023-12-01 05:00:41 25 4
gpt4 key购买 nike

我有一个包含以下内容的索引页面:-

<ul>
<li><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
</ul>
<div ng-view></div>

以下是我的路由脚本:-
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'home.html',
controller : 'homeController'
}).when('/about', {
templateUrl : 'about.html',
controller : 'aboutController'
});
});

我可以将 Controller 保存在 templateUrl 文件中吗?如下图:-

关于.html
<script>
app.controller('aboutController', function($scope) {
$scope.message = 'This is About Us page.';
});
</script>
<h1>About Us</h1>
<p>{{ message }}</p>

最佳答案

是的,您可以将 Controller 保留在模板中。

index.html

<head>

<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.1/angular-route.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>

<body ng-app="myApp">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div>
<ul class="nav navbar-nav">
<li>
<a href="#home">Home</a>
</li>
<li><a href="#about">About</a></li>
</ul>
</div>

</div>
</nav>
<div ng-view></div>


<script>
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'homeController'
}).when('/about', {
templateUrl: 'about.html',
controller: 'aboutController'
});
});
app.controller('aboutController', function($scope) {
console.log("aboutController");
$scope.message = 'This is about page.';
});
app.controller('homeController', function($scope) {
console.log("homeController");
$scope.message = 'This is Home page.';
});
</script>
</body>

</html>

首页.html about.html 我保持不变
<h3> {{message}}</h3>

您可以查看演示 here .

关于angularjs - 我可以在 AngularJS 的模板文件中保留 Controller 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33079747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com