2014-03-27 55 views
1

我一直在Dan Wahlin的電子書中傾聽AngularJS。筆者有試過約模塊,路由和工廠從第53頁然後解釋,我寫的代碼作爲index.html的:無法在Angularjs中路由

<div class="container" data-ng-app="demoApp"> 
<div> 
    <h3>Adding Module Configuration and Routing</h3> 
    <!-- ng-view handles loading partials into it based 
     upon routes --> 
    <div data-ng-view=""></div> 
</div> 
</div> 


<script type="text/javascript" src="js/angular.js"></script> 
<script type="text/javascript"> 
var demoApp = angular.module('demoApp', []); 

demoApp.config(function ($routeProvider) { 
    $routeProvider 
      .when('/view1', 
      { 
       controller: 'SimpleController', 
       templateUrl: urlBase + 'View1.html' 
      }) 
     //Define a route that has a route parameter in it (:customerID) 
      .when('/view2', 
      { 
       controller: 'SimpleController', 
       templateUrl: urlBase + 'View2.html' 
      }) 
      .otherwise({ redirectTo: '/View1' }); 
}); 

demoApp.controller('SimpleController', function ($scope) { 
    $scope.customers = [ 
     { name: 'Dave Jones', city: 'Phoenix' }, 
     { name: 'Jamie Riley', city: 'Atlanta' }, 
     { name: 'Heedy Wahlin', city: 'Chandler' }, 
     { name: 'Thomas Winter', city: 'Seattle' } 
    ]; 
}); 

$scope.addCustomer = function() { 
    $scope.customers.push({ name: $scope.newCustomer.name, city: $scope.newCustomer.city  }); 
} 


</script> 

然後,我創建了兩個html頁面 - View1.htmlView2.html,並在視圖1。 HTML,我寫道:

<div class="container"> 

    <h3>View 1</h3> 

    Name<br /> 
    <input type="text" data-ng-model="filter.name" /> 
    <br /> 
    <ul> 
     <li data-ng-repeat="cust in customers | filter:filter.name"> 
      {{ cust.name }} - {{ cust.city }} 
     </li> 
    </ul> 

    <br />Customer Name<br /> 
    <input type="text" data-ng-model="newCustomer.name" /> 
    <br /> 

    <br />Customer City<br /> 
    <input type="text" data-ng-model="newCustomer.city" /> 
    <br /> 

    <button data-ng-click="addCustomer()">Add Customer</button> 
    <br /> 
    <a href="#/view2">View 2</a> 

</div> 

當我瀏覽爲http://localhost/angular/index.html#/view1,我沒有看到任何的意思是沒有輸出。實際上我不明白我在哪裏做錯了。

回答

1

這裏最大的問題是,你不包括routing module,這是自角1.2+

<script type="text/javascript" src="js/angular.js"></script> 
<script type="text/javascript" src="js/angular-route.js"></script> 

<script type="text/javascript"> 

var demoApp = angular.module('demoApp', ['ngRoute']); 

//Snip... 

</script> 

需要正如goutham in the comments提到的,你還需要定義urlBase您不會出現在任何地方做。

因爲JavaScript爲字符串連接輸入了強制轉換,所以最後會在您的templateUrl後面添加單詞'undefined'。

console.log(undefined + "view1.html"); // 'undefinedview1.html' 
+1

另外'var base_url =「someUrl」;'應該添加在配置函數的頂部。 – goutham

+0

謝謝@Josh和goutham。你的兩個建議對我有幫助。只需要知道一件事,那就是我現在無法添加客戶。你能告訴我嗎? – StreetCoder

+0

我通過自己修復了它。不過,非常感謝 – StreetCoder