【问题标题】:Problems with Angular state and resolveAngular 状态问题和解决方法
【发布时间】:2015-12-11 20:36:53
【问题描述】:

我正在努力学习平均堆栈,并且被 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 中的代码并发送一个警告框,上面写着 test.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>

任何关于为什么在页面加载时没有触发警报的建议将不胜感激。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 这么简单,谢谢。
    • @Chris 很高兴为您提供帮助.. 谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 2021-11-08
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    相关资源
    最近更新 更多