簡體   English   中英

角度狀態問題和解決方法

[英]Problems with Angular state and resolve

我正在研究均值堆棧,並且開始使用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> 

任何有關為什么在頁面加載時未觸發警報的建議,將不勝感激。

您應該從factory返回o ,因為factory返回一個對象。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM