简单示例无法访问范围

时间:2016-11-17 16:29:22

标签: javascript angularjs

我正在尝试学习AngularJS,并通过一个较旧的教程,我已经构建了一个简单的应用程序。它有一个index.html和两个部分视图,通过ui-router加载。我知道它没有被分成不同的文件 - 这只是一个学习项目。

问题是$ Scope在View1或其调用的JS函数中似乎不可用,因此ng-repeat似乎找不到要显示的内容,addCustomer看不到$ scope.newCustomer.name。我确信我错过了一些简单的事情。

的index.html:

<!DOCTYPE html>
<html ng-app="demoApp">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
  <title></title>
  <script src="js/angular/angular.js"></script>
  <script src="js/angular-ui-router/angular-ui-router.js"></script>
  <!-- your app's js -->
  <script>

 var demoApp = angular.module('demoApp', ['ui.router']); // [] is for dependencies

// routes
demoApp.config(function($stateProvider, $urlRouterProvider) {
  var nameState = {
    name: 'name',
    url: '/view1',
    controller: 'SimpleController',
    templateUrl: 'partials/View1.html'
  }

  var cityState = {
    name: 'city',
    url: '/view2',
    controller: 'SimpleController',
    templateUrl: 'partials/View2.html'
  }

  $stateProvider.state(nameState);
  $stateProvider.state(cityState);

  $urlRouterProvider.otherwise('/view1');
});

 // controller

demoApp.controller("SimpleController", function ( $scope, $log ) {
    $scope.log = $log;

    $scope.customers = [{name: 'John Doe', city:'New York'}, 
                        {name: 'Jake Smith', city:'Atlanta'}, 
                        { name: 'Jane Doe', city:'San Francisco'}];


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

</script>
</head>

<body>
  <div>
    <!-- placeholder for views inserted by ui-router -->
    <ui-view></ui-view>
  </div>
</body>

</html>

View1.html

<div class="container">
  <h2>View 1</h2>
  Name: <input type="text" ng-model="filter.name" /> You entered:  {{filter.name}}
  <div class="container">
    <h3> Loop </h3>
    <ul>
      <li ng-repeat="cust in $scope.customers | filter:filter.name">{{ cust.name }} - {{ cust.city }}</li>
    </ul>
    <br /> Customer Name:
    <input type="text" ng-model="newCustomer.name" />
    <br /> Customer City:
    <input type="text" ng-model="newCustomer.city" />
    <br />
    <br />
    <button ng-click="addCustomer()">Add Customer</button>
  </div>
  <a href="#/view2">Switch to View 2</a>
</div>

4 个答案:

答案 0 :(得分:1)

仅限使用

ng-repeat="cust in customers"

答案 1 :(得分:1)

您不必在html中指定$ scope:

ng-repeat="cust in customers"

答案 2 :(得分:1)

试试这个:

<li ng-repeat="cust in customers">

你不需要提及$scope.customers

答案 3 :(得分:1)

试试这个(删除“$ scope。”):

ng-repeat="cust in customers | filter:filter.name"

而不是:

ng-repeat="cust in $scope.customers | filter:filter.name"