我正在尝试使用AngularJS并在其上做一些基础。这是我的观点:
<body ng-app="flapperNews">
<div align="center">
<ui-view></ui-view>
</div>
<script type="text/ng-template" id="/home.html">
<h1>Flapper News</h1>
<div ng-repeat="post in posts | orderBy:'-upvotes'">
{{post.upvotes}}
{{post.title}}
{{post.title}}
</div>
<form ng-submit="addPost()">
<h3>Add a new post</h3>
<input type="text" placeholder="Title" ng-model="title"></input>
<input type="text" placeholder="Link" ng-model="link"></input>
<button type="submit" >Post</button>
</form>
</script>
</body>
此视图由app.js处理:
angular.module('flapperNews', [])
.controller('MainCtrl', function($scope) {
$scope.posts = [
{title: 'post 1', upvotes: 0},
{title: 'post 2', upvotes: 0},
{title: 'post 3', upvotes: 0},
{title: 'post 4', upvotes: 0},
];
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
upvotes: 0});
$scope.title = '';
};
$scope.incrementUpvotes = function(post){
post.upvotes += 1;
};
});
angular.module('flapperNews', ['ui.router'])
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}])
问题是帖子数据未在页面上呈现。但是,如果我不使用ui.router
和<ui-view>
来渲染模板,那么它正在运行; (表示帖子数据可以显示在页面上)。
那么,问题是什么,我该如何纠正?
答案 0 :(得分:2)
您正在声明模块两次 - 声明模块是您将第二个参数放入模块函数时,而如果您只想引用它,则省略第二个参数。
基本上,您的代码应为:
angular.module('flapperNews', ['ui.router']) // declaration here
.controller('MainCtrl', function($scope) {
$scope.posts = [
{title: 'post 1', upvotes: 0},
{title: 'post 2', upvotes: 0},
{title: 'post 3', upvotes: 0},
{title: 'post 4', upvotes: 0},
];
$scope.addPost = function(){
if(!$scope.title || $scope.title === '') { return; }
$scope.posts.push({
title: $scope.title,
upvotes: 0});
$scope.title = '';
};
$scope.incrementUpvotes = function(post){
post.upvotes += 1;
};
});
angular.module('flapperNews') // reference only here
.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl'
});
$urlRouterProvider.otherwise('home');
}])
答案 1 :(得分:0)
所以在角度
angular.module('flapperNews', [list dependencies]);
创建一个新模块和
angular.module('flapperNews')//notice there is no array
返回模块。
我认为您的意思是将['ui.router']
移到app.js文件的顶行。