【问题标题】:Pushing string to Array in Ionic在离子中将字符串推送到数组
【发布时间】:2016-03-05 00:43:32
【问题描述】:

大家好,我正在尝试学习 Angular 来制作 Ionic 应用程序,并且我正在学习关于 Angular 的教程,问题是并非所有 Angular 语句都适用于 Ionic。我试图将名称和城市从输入推送到数组(不需要保存它们。

这些是我的输入字段:

<p>What is your first name? </p>
<input type="text" ng-model="newCustomer.name"/>
<p>What city do you live in?</p>
<input type="text" ng-model="newCustomer.city"/>
<button ng-click="addCustomer()">Become a customer</button>

这是所有名称和城市的显示方式:

<ul>
   <li ng-repeat="cust in customers | filter: name"> {{cust.name + " from " + cust.city}} </li>
</ul>

这是控制器:

demoApp.controller('simpleController', function ($scope){
    $scope.customers =  [
        { name: 'jasper', city: 'Amsterdam' },
        { name:'Dave',city:'phoenix'} ,
        { name:'Gina', city:'Amsterdam' },
        { name: 'Philip', city:'Otterloo'}
        ];

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

我正在关注一个教程,我在堆栈和谷歌上进行了搜索,但真的找不到我做错了什么,我希望有人能帮助我。

附:我是堆栈的新手,所以如果我做错了什么(堆栈规则明智),请不要犹豫向我指出。

编辑:有人要求提供完整的 app.js 代码

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

demoApp.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/')

    $stateProvider.state('home', {
  url: '/home',
  views: {
    home: {
      templateUrl: 'home.html',
        controller: 'simpleController'
    }
  }
})

$stateProvider.state('help', {
  url: '/help',
  views: {
    help: {
      templateUrl: 'help.html',
        controller: 'simpleController'

    }
  }
})
});

demoApp.controller('simpleController', function ($scope){
    $scope.customers =  [
        { name: 'jasper', city: 'Amsterdam' },
        { name:'Dave',city:'phoenix'} ,
        { name:'Gina', city:'Amsterdam' },
        { name: 'Philip', city:'Otterloo'}
        ];

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

【问题讨论】:

  • 尝试做一个console.log,看看你是否可以在模拟器中调试它
  • 感谢控制台中出现此错误:“TypeError: Cannot read property 'name' of undefined at Scope.$scope.addCustomer” in my app.js
  • 虽然还没找到解决办法
  • 您的代码看起来 100% 正确,您在其他页面上进行了一些更改可能是
  • 能否展示app.js的完整代码

标签: javascript angularjs ionic-framework


【解决方案1】:

我找到了答案,不,我的代码不正确。 解决方案是:

    $scope.newCustomer= {};

就在控制器下方,问题在于 newCustomer 未定义。

谢谢大家帮助我。

编码愉快!

编辑:感谢 Khanh TO 在此堆栈 pos 上找到了他的答案:Why ng-model is not defined?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2018-02-17
    • 2020-10-07
    • 2021-02-17
    • 2017-08-31
    相关资源
    最近更新 更多