0

我正在使用 Angular 种子(从 Angular 网页下载),并试图在部分 . 这是代码:

应用程序.js

'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives',      'myApp.controllers']).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partials/partial1.html', controller:   'mainPage'});
  $routeProvider.when('/view2', {templateUrl: 'partials/partial2.html', controller: 'MyCtrl2'});
   $routeProvider.otherwise({redirectTo: '/view1'});

   }]);

控制器.js

'use strict';

 /* Controllers */

angular.module('myApp.controllers', []).
controller('mainPage', ['$scope',function() {

  $scope.data= "this is my data";
}])
  .controller('MyCtrl2', [function() {

 }]);

索引.html

<!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>My AngularJS App</title>
<link rel="stylesheet" href="css/app.css"/>
</head>
<body>
<ul class="menu">
<li><a href="#/view1">view1</a></li>
<li><a href="#/view2">view2</a></li>
</ul>

<div ng-view></div>
... some more angular includes etc

部分1.html

<p>This is the partial for view 1. {{data}}</p>

我期待看到控制器中定义的数据,但我只是看到:“这是视图 1 的部分。{{data}}”

4

2 回答 2

2

我认为主要问题是您没有将 $scope 传递给控制器​​功能。您应该在浏览器控制台上收到错误消息。在这里查看工作中的 Plunker:

http://plnkr.co/edit/ItziGeIVI5a9L56P1UCx

var myApp = angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view1', {templateUrl: 'partial1.html', controller:   'mainPage'});
  $routeProvider.when('/view2', {templateUrl: 'partial2.html', controller: 'MyCtrl2'});
   $routeProvider.otherwise({redirectTo: '/view1'});

   }]);

myApp.controller('mainPage', ['$scope',function($scope) {
  $scope.data = "this is my data";
}])
.controller('MyCtrl2', ['$scope', function($scope) {
  $scope.data = "this is my data 2";
}]);
于 2013-09-18T14:50:42.280 回答
1

这个:

controller('mainPage', ['$scope', function() {
  $scope.data= "this is my data";
}])

应该:

controller('mainPage', ['$scope', function($scope /* ADD THIS */) {
  $scope.data= "this is my data";
}])
于 2013-09-18T14:45:08.390 回答