我无法在控制器中获取声明的范围变量。相反,我得到了reference error : message is not defined
以下是我的代码:
我的Index.html
<body ng-app="myApp" ng-controller="homingController" ng-cloak>
<script type="text/javascript">
angular.module('myApp' ['ngRoute','ngMaterial']).controller('homingController', ['$scope',
function($scope){
$scope.message = 'Hello';
}
]).config(function ($routeProvider) {
$routeProvider.when("/home", {
templateUrl: "home.html",
controller: "homingController"
}).when("/monitor", {
templateUrl: "monitor.html",
controller: "monitoringController"
}).otherwise({
redirectTo: '/home'
});
}).controller('monitoringController', function ($scope) {
$scope.message = "Monitor";
});
</script>
<nav class = "navbar navbar-inverse" role="navigation">
<ul class = "nav navbar-nav" >
<li ><a href="#!/home" class = "active" ui-sref= "home" style="margin: 0px 1px 0px 19px"><img src="./images/home.svg">Home</a></li>
<li ><a href="#!/monitor" class = "active" ui-sref = "monitor" ><img src="./images/monitor.svg">Monitor</a></li>
<li ><a class = "active" ui-sref = "Audit" ><img src="./images/audit.svg">Audit</a></li>
<li ><a class = "active" ui-sref = "configuration" ><img src="./images/configure.svg">Configure</a></li>
</ul>
</nav>
</div>
</body>
<div ng-view></div>
我的home.html
{{ message}}
/*This line giving error in console : angular.js:14328 ReferenceError: $scope is not defined
*/
这里有什么我想念的吗?
答案 0 :(得分:1)
您的<div ng-view></div>
应该在<body>
标记内。通过将其放置在您定义应用程序的正文之外,视图不知道应该使用哪个应用程序或控制器。
您也无需在视图的任何位置标识ng-controller
,因为您在routeconfig中定义了它们:
var app = angular.module('myApp' ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when("/home", {
templateUrl: "home.html",
controller: "homingController"
}).when("/monitor", {
templateUrl: "monitor.html",
controller: "monitoringController"
}).otherwise({
redirectTo: '/home'
});
});
app.controller('homingController', function($scope) {
$scope.message = 'Hello';
})
app.controller('monitoringController', function($scope) {
$scope.message = "Monitor";
});
如果您想显示某个控制器中的某些内容,您应该这样定义:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="homingController">
{{message}}
</div>
<nav class="navbar navbar-inverse" role="navigation">
<ul class="nav navbar-nav">
<li>
<a href="#!/home">Home</a>
</li>
<li>
<a href="#!/monitor">Monitor</a>
</li>
</ul>
</nav>
<div ng-view></div>
</body>
使用home.html
&amp; monitor.html
包含{{ message }}
。可以在w3Schools(在“控制器”标题下)找到这方面的确切示例。构建它,然后一旦你有工作开始扩展它,以填写你的应用程序的其余部分。