2016-02-14 14 views
0

我正在嘗試使用AngularJS並對其進行一些基本的設置。這是我的看法:ThinkThread上的AngularJS教程

<body ng-app="flapperNews"> 
    <div align="center"> 
    <ui-view></ui-view> 
    </div> 
<script type="text/ng-template" id="/home.html"> 
    <h1>Flapper News</h1> 
     <div ng-repeat="post in posts | orderBy:'-upvotes'"> 

     {{post.upvotes}} 

      {{post.title}} 

      {{post.title}} 

     </div> 

     <form ng-submit="addPost()"> 
     <h3>Add a new post</h3> 
     <input type="text" placeholder="Title" ng-model="title"></input> 
     <input type="text" placeholder="Link" ng-model="link"></input> 
     <button type="submit" >Post</button> 
     </form> 

</script> 

</body> 

這一觀點由app.js處理:

angular.module('flapperNews', []) 
.controller('MainCtrl', function($scope) { 


     $scope.posts = [ 
      {title: 'post 1', upvotes: 0}, 
      {title: 'post 2', upvotes: 0}, 
      {title: 'post 3', upvotes: 0}, 
      {title: 'post 4', upvotes: 0}, 

     ]; 
     $scope.addPost = function(){ 
      if(!$scope.title || $scope.title === '') { return; } 
      $scope.posts.push({ 
       title: $scope.title, 
       upvotes: 0}); 
      $scope.title = ''; 
     }; 

     $scope.incrementUpvotes = function(post){ 
      post.upvotes += 1; 
     }; 

}); 

angular.module('flapperNews', ['ui.router']) 
.config([ 
'$stateProvider', 
'$urlRouterProvider', 
function($stateProvider, $urlRouterProvider) { 

    $stateProvider 
    .state('home', { 
     url: '/home', 
     templateUrl: '/home.html', 
     controller: 'MainCtrl' 
    }); 

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

問題是,POST數據不呈現頁面上。但是,如果我不使用ui.router<ui-view>來呈現模板,那麼它正在運行; (意味着帖子的數據可以顯示在頁面上)。

那麼,什麼是問題,我該如何糾正?

回答

2

你聲明你的模塊兩次 - 聲明模塊是當你把第二個參數放在模塊函數中,而如果你只是想引用它,你可以省略第二個參數。

基本上,你的代碼應該是:

angular.module('flapperNews', ['ui.router']) // declaration here 
.controller('MainCtrl', function($scope) { 


     $scope.posts = [ 
      {title: 'post 1', upvotes: 0}, 
      {title: 'post 2', upvotes: 0}, 
      {title: 'post 3', upvotes: 0}, 
      {title: 'post 4', upvotes: 0}, 

     ]; 
     $scope.addPost = function(){ 
      if(!$scope.title || $scope.title === '') { return; } 
      $scope.posts.push({ 
       title: $scope.title, 
       upvotes: 0}); 
      $scope.title = ''; 
     }; 

     $scope.incrementUpvotes = function(post){ 
      post.upvotes += 1; 
     }; 

}); 

angular.module('flapperNews') // reference only here 
.config([ 
'$stateProvider', 
'$urlRouterProvider', 
function($stateProvider, $urlRouterProvider) { 

    $stateProvider 
    .state('home', { 
     url: '/home', 
     templateUrl: '/home.html', 
     controller: 'MainCtrl' 
    }); 

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

它現在工作,非常感謝你! –

+0

不客氣,很高興我能提供幫助。 :) – Shomz

0

所以在角

angular.module('flapperNews', [list dependencies]); 

創建一個新的模塊和

angular.module('flapperNews')//notice there is no array 

返回模塊。

我想你的意思是將['ui.router']移動到你的app.js文件的第一行。