为什么$ scope对象无法在view2.html中显示来自控制器的数据

时间:2019-01-22 19:55:16

标签: angularjs ngroute

我是新的Angular JS。我坚持使用$ routeProvider示例。从main.html.View1正常工作时,我使用$ routeProvider。路由view1和view2。 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>

0 个答案:

没有答案