【发布时间】:2016-04-23 04:40:44
【问题描述】:
我正在学习 angularjs,其中有一个方面我很难理解。
我对以下代码的期望/预期行为是:
- 用户点击巴黎链接(锚标签)
- routeProvider 拦截请求,将 paris.html 页面加载到 ng-view 中。
- 控制器中的“getCity”函数获取数据并设置范围变量,这些变量显示在 london.html 表达式中。
但是,当 html 页面加载到 ng-view 中时,我无法弄清楚如何配置 angularjs 以使用“getCity”功能。我能得到的最接近的是从 CityController 本身调用“getCity”函数,这似乎有在加载整个应用程序(index.html)而不是仅在单击链接时调用该函数的不良影响。控制器将具有许多不同的功能。
我也知道您可以使用 ng-click 调用控制器的函数,但我不确定这将如何通过路由提供程序将 html 页面加载到 ng-view 中。
任何帮助将不胜感激。请参阅以下为学习目的而构建的小应用程序的代码:
index.html
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-route.js"></script>
</head>
<body>
<ol>
<li><a href="#/cities/paris">Paris</a></li>
</ol>
<div class="content-wrapper" ng-controller="CityController">
<div ng-view></div>
</div>
<script src="resources/js/app.js"></script>
<script src="resources/js/CityController.js"></script>
</body>
</html>
app.js
var app = angular.module("mainApp", [ 'ngRoute' ]);
app.config([ '$routeProvider', function($routeProvider) {
$routeProvider.
when('/cities/paris', {
templateUrl : 'resources/paris.html',
controller : 'CityController'
}).
otherwise({
redirectTo : ''
});
} ]);
CityController.js
app.controller('CityController', function($scope, $http) {
$scope.getCity = function() {
$http.get('city')
.success(function(response) {
$scope.name = response.name;
$scope.country = response.country;
}).error(function() {
//Output error to console
});
};
//$scope.getCity();
});
我不想在这里调用 getCity 因为这意味着 http get 请求 加载 index.html 时调用 'city' 端点
paris.html
This is Paris.
<br><br><br>
Name: {{name}}<br>
Country: {{country}}
<br><br><br>
【问题讨论】:
标签: javascript angularjs