AngularJS 表达式不显示来自服务的数据

AngularJS Expression not displaying the data from service

我怀疑这是一个不正确的表达式或控制器从服务中获取数据的方式。顺便说一句,控制器已经过测试并且工作正常。 请帮忙。

这是我的看法

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="js/vendor/angular.min.js"></script>
<!-- Installing the ngRoute module -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular-route.js"></script>
</head>
<body ng-app="SuggestionBox">
    <div class="suggestion" ng-controller="HomeController">
        <div class="container" ng-repeat="post in posts">
        <h2 class="title">{{ post.title }}</h2>
        </div>
    </div>

<script src="js/app.js"></script>
<!-- Controllers -->
<script src="js/controllers/HomeController.js"></script>
<!-- Services -->
<script src="js/services/suggestions.js"></script>
</body>
</html>

这是我从中获取数据的服务

app.factory('suggestions', [function() {
var demoSuggestions = {
    posts: [
        {
            title: "bla bla bla",
        },
        {
            title: "blo blo blo",
        }
    ]
};
return demoSuggestions;
}]);

这是控制器

app.controller('HomeController', ['$scope', 'suggestions', function($scope, suggestions) {
$scope.posts = suggestions.demoSuggestions;
}]);

在服务中,您应该分配 posts,它已在 suggestions 工厂对象中 return。

控制器

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

Demo here

更新

你app.js应该像下面这样定义模块

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

编辑

我做了最后一个 plunkr 来演示 OP 所面临的问题。所以理想情况下,您应该遵循 John Papa

制作的 angular styleguide

这里需要将每个组件代码包装成IIFE模式,如

(function(){
  //code here
})()

并定义angular module一次并在之后使用它们,避免创建全局变量。