我无法让AngularJS加载我的服务

时间:2017-04-18 05:25:13

标签: angularjs

我写这篇文章是为了获得有关AngularJS的问题的帮助。这是我的编码教育中的一个重新解决问题,因为无论如何,编码中最大的问题始终是如何将文件链接在一起。在AngularJS中,它一直让我感到不安,因为我已经尝试了几个月才能使我的代码工作,甚至无法在基本级别上链接它,因此编写更多代码是没用的。

我会发布我的HTML和我所有的AngularJS文件给你看,请告诉我它做错了什么,以及如何防止这种情况发生在将来。我正在做一个codecademy fullstack课程,我还需要添加ReactJS和Jquery。我将Jquery过渡到我网站的所有其他部分,但我担心一旦我试图将它放在这里就会出现问题。

P.S。我不知道如何在JSfiddle中制作多个Javascript文件,但我希望它能做到。

代码:

var app = angular.module("SugesstionBox", []);

// my HomeController.js file

app.controller("HomeController", ['$scope', 'suggestions' function($scope, suggestions){
    $scope.posts = suggestions.posts;
   $scope.message = "AngularJS Tutorial";
}]);

// My suggestions.js service file

app.factory('suggestions', [function(){
    var demosuggestions = {
        posts: [
            {
            title: 'free pizza is amazing!',
            upvotes: 1,
            comments: [],
            },
            {

            title: 'free pizza is still amazing!',
            upvotes: 5,
            comments: [],
            }

        ]

    };
    return demosuggestions;
}]);

Complete example on JSFiddle.

2 个答案:

答案 0 :(得分:0)

检查这个

https://jsfiddle.net/durga598/9znr99ku/2/

在html设置标签中放置<body ng-app="SugesstionBox"> 并在javascript标签LOAD TYPE:-No-wrap in <body>

答案 1 :(得分:0)

AS tanmay说你错过了正确的声明并在你的小提琴中调用你的脚本,而这些脚本在小提琴中是不可用的..... 更多我建议你使用ng -if作为评论确实显示更好的视图,如下所示post.upvotes而不是post.upvote

var app = angular.module('plunker', []);

app.controller("HomeController", ['$scope', 'suggestions', function($scope, suggestions){
    $scope.posts = suggestions.posts;
   $scope.message = "AngularJS Tutorial";
}]);
app.factory('suggestions', [function(){
    var demosuggestions = {
        posts: [
            {
            title: 'free pizza is amazing!',
            upvotes: 1,
            comments: [],
            },
            {
                
            title: 'free pizza is still amazing!',
            upvotes: 5,
            comments: [],
            }
            
        ]
        
    };
    return demosuggestions;
}]);
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="HomeController">
    <div>
            {{ message }}
        </div>
        <div ng-repeat="post in posts">
        <div>
        {{post.title}}</div>
        <div>
        {{post.upvotes}}</div>
        <div ng-if="post.comments.length>0">
        {{post.comments}}</div>
        </div>
  </body>

</html>