首页 > 解决方案 > 为什么 $scope 对象无法在 view2.html 中显示来自我的控制器的数据

问题描述

我是新的 Angular JS。我坚持使用 $routeProvider 示例。我正在使用 $routeProvider 路由 view1 和 view2。当来自 main.html.View1 工作正常时。View2 没有得到 $scope 对象。

View1 正在显示客户数据。但是 View2 不工作。我是否错过了代码中的某些内容。

##Main.html:
    <html ng-app="demoApp">
        <title>AngularJS Routing</title>
        <body>

          <div>
            <ng-view></ng-view>
          </div>
        <script src="angular.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>

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

    demoApp.config(function($routeProvider) 
    {
        $routeProvider
        .when('/',{controller:'Controller1',templateUrl:'view1.html'})
        .when('/view2',{controller:'Controller1',templateUrl:'view2.html'})
        .otherwise({redirectTo:'/view1.html'});
    });
    demoApp.controller("Controller1", function($scope) 
    {
       $scope.customers = [
           {custname:"A",city:"Irving"},
           {custname:"B",city:"Grapevine"},
           {custname:"C",city:"Little Elm"},
           {custname:"D",city:"Frisco"},
           {custname:"E",city:"Mckinney"},
           {custname:"F",city:"Prosper"}
       ];

       $scope.addItem = function(){
           $scope.customers.push({
               custname:$scope.newCustomername,
               city:$scope.newCustomercity
           });
       }   
    });

</script>
</body>
</html>

##view1.html:

    <div class="container">
        <h2>Welcome to Directive - Data Binding</h2>

        Customer Name: <input type="text" data-ng-model="newCustomername"> 
        Customer City: <input type="text" data-ng-model="newCustomercity">
        <button ng-click="addItem()">Add Item</button>

        <li ng-repeat="name in customers"> 
           Customer Name: {{ name.custname }} <br/> 
           Customer City: {{ name.city }} 
        </li>
        <a href="#/view2">View 2</a>

    </div>

##View2.html:

    <div class="container">
        <h3> View 2</h3>
        <li ng-repeat="name in customers"> 
            Customer Name: {{ name.custname }} <br/>
            Customer City: {{ name.city }} 
        </li> 

    </div>

标签: angularjsngroute

解决方案


推荐阅读