gpt4 book ai didi

javascript - 无法从 Thinkster MEAN Stack 教程中获得工作支持

转载 作者:行者123 更新时间:2023-12-03 06:26:14 24 4
gpt4 key购买 nike

我一直在浏览this MEAN Stack 教程在后面,但是我已经更改了我的代码以使用 Controller as 而不是像他们在代码中那样使用 $scope

我被困在启用赞成票部分。当我点击它时,点赞数并没有增加,我不确定为什么会发生这种情况。

谁能帮忙解决这个问题吗?这是我的代码:

index.html

<html>
<head>
<title>My Angular App!</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="flapperNews" ng-controller="MainCtrl as main">
<div ng-repeat="post in main.posts | orderBy: '-upvotes'">
<span ng-click="incrementUpvotes(post)">^</span>
{{ post.title }} - upvotes: {{ post.upvotes }}
</div>
<form ng-submit="main.addPost()">
<input type="text" ng-model="main.title"></input>
<button type="submit">Add Post</button>
</form>
</body>
</html>

app.js

/*global angular*/
/*jslint white:true*/
angular
.module('flapperNews', [])
.controller('MainCtrl', function(){
'use strict';
var main = this;

main.posts = [
{title: 'post 1', upvotes: 5},
{title: 'post 2', upvotes: 2},
{title: 'post 3', upvotes: 15},
{title: 'post 4', upvotes: 9},
{title: 'post 5', upvotes: 4}
];

main.addPost = function(){
if(!main.title || main.title === '') {return;}
main.posts.push({title: main.title, upvotes: 0});
main.title = '';
};

main.incrementUpvotes = function(post) {
post.upvotes += 1;
};
});

最佳答案

您遇到的问题是ng-repeat。您需要将代码更改为 $parent.incrementUpvotes(post) 才能完成此操作。

原因如下:ng-repeat 为每次迭代创建一个新的子作用域,但您无法完全访问您可能需要的所有内容。这是由于 Angular 如何将属性复制到子作用域中。为了访问实际包含 incrementUpvotes 定义的作用域( Controller 作用域),您需要首先向上移动到父作用域。或者,您也可以执行 main.incrementUpvotes(post) 来完成相同的操作,因为您为 Controller 添加了别名。

您可以在此处查看更详细的解释,了解 Angular 创建子作用域时会发生什么,以及为什么某些属性不被继承 https://github.com/angular/angular.js/wiki/Understanding-Scopes

What happens is that the child scope gets its own property that hides/shadows the parent property of the same name. This is not something AngularJS is doing – this is how JavaScript prototypal inheritance works. New AngularJS developers often do not realize that ng-repeat, ng-switch, ng-view and ng-include all create new child scopes, so the problem often shows up when these directives are involved.

关于javascript - 无法从 Thinkster MEAN Stack 教程中获得工作支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38645651/

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