Angular状态和解决问题

时间:2015-12-11 20:36:53

标签: javascript angularjs angular-ui-router angular-promise angularjs-factory

我正在努力学习平均堆栈,并且正在使用Angular和路由器绊倒。我有一个javascript文件,下面列出了包含app.config模块中的路由代码。

var app = angular.module('doorSensorReadings', ['ui.router']);

app.factory('readings',  ['$http', function($http){
  var o = {
    readings: []
  };
  
  o.getAll = function() {
		alert("test");
	};
}])

app.controller('MainCtrl', ['$scope', 'readings', function($scope, readings){
  $scope.readings = readings.readings;  
 
  $scope.addReading = function(){
    $scope.readings.push({id: 2, name:"Door 4", open: true})
  }
  
}]);

app.config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: '/home.html',
      controller: 'MainCtrl',
      resolve: {
        Promise: ['readings', function(readings){
          return readings.getAll();
        }]
      }
    });

  $urlRouterProvider.otherwise('home');
}]);

当页面加载时,我希望它会触发app.factory中的代码并发送一个显示测试的警告框。我无法弄清楚为什么代码没有被调用,我加载页面时没有收到任何错误。现在它只是加载一个空白页面。 “ejs”文件如下:

<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="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
  <script src="javascripts/angularApp.js"></script>
</head>

<body ng-app="doorSensorReadings">
  
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <ui-view></ui-view>
    </div>
  </div>


<script type="text/ng-template" id="/home.html">
  <div class="page-header">
    <h1>Door Sensor</h1>
    
    <div ng-repeat="reading in readings">
      {{reading.id}}, {{reading.name}}, {{reading.open}}
    </div>

    <button ng-click="addReading()">Post</button>
  </div>
</script>

</body>

</html>

任何有关在加载页面时未触发警报的建议都将非常感激。

1 个答案:

答案 0 :(得分:1)

您应该从o返回factory,因为工厂会返回一个对象。

app.factory('readings',  ['$http', function($http){
  var o = {
    readings: []
  };

  o.getAll = function() {
     alert("test");
  };
  return o;
}])