我正在使用Angular种子(从angular网页下载)并且我试图在部分内部显示范围控制器中的数据。 这是代码:
app.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'});
}]);
controllers.js
'use strict';
/* Controllers */
angular.module('myApp.controllers', []).
controller('mainPage', ['$scope',function() {
$scope.data= "this is my data";
}])
.controller('MyCtrl2', [function() {
}]);
的index.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
partial1.html
<p>This is the partial for view 1. {{data}}</p>
我期待看到控制器中定义的数据,但我只是看到: “这是视图1的部分内容。{{data}}”
答案 0 :(得分: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";
}]);
答案 1 :(得分:1)
此:
controller('mainPage', ['$scope', function() {
$scope.data= "this is my data";
}])
应该是:
controller('mainPage', ['$scope', function($scope /* ADD THIS */) {
$scope.data= "this is my data";
}])