gpt4 book ai didi

javascript - Thinkster 教程上的 AngularJS

转载 作者:行者123 更新时间:2023-12-02 15:01:50 25 4
gpt4 key购买 nike

我正在尝试使用 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>

此 View 由 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>对于渲染模板,它正在工作; (表示页面可以显示帖子的数据)。

那么,问题是什么?我该如何纠正?

最佳答案

您声明了模块两次 - 声明模块是在将第二个参数放入模块函数中时进行的,而如果您只想引用它,则可以省略第二个参数。

基本上,您的代码应该是:

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');
}])

关于javascript - Thinkster 教程上的 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35388478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com