简单的例子可以't访问范围

Simple example can't access scope

本文关键字:访问 范围 简单      更新时间:2023-09-26

我正在尝试学习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>

只能使用

ng-repeat="cust in customers"

你不必在html中指定$scope:

ng-repeat="cust in customers"

try this:

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

你不需要提及$scope.customers

试试这个(删除"美元范围。"):

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

代替:

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