我可以将控制器保存在AngularJS的模板文件中吗?

时间:2015-10-12 11:16:08

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat angularjs-service

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

<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'
    });
});

我可以将控制器保存在templateUrl文件中吗?如下所示: -

about.html

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

1 个答案:

答案 0 :(得分:1)

是的,您可以将控制器保留在模板中。

<强>的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>

home.html about.html 我保持不变

<h3> {{message}}</h3>

您可以查看演示here