AngularJS 来自 ng-model 的 $scope 值在同一个控制器中从一个页面到另一个页面丢失 - Ionic Framework

AngularJS $scope values from ng-model lost from page to page in same controller - Ionic Framework

我有这个页面,它将 input.countNum 范围变量链接到带有 ng-model 的输入。按钮上显示的值显示正常。当您单击第一页上的按钮时,它会导航到第二页,该页面也显示范围变量。但是变量在控制器代码中被重置为默认声明值。

如何在同一控制器内的页面之间维护 ng-model 的范围值?

tab-dash.html

<ion-view view-title="Test">

  <ion-content class="padding">

    <div class="list">

        <label class="item item-input">
            <span class="input-label">Count</span>
            <input class="text-right" type="number" pattern="[0-9]*" ng-model="input.countNum">
        </label>

    </div>

    <button class="button button-full button-positive" ng-click="create()" ui-sref="tab.count">
        Count is ({{input.countNum}})
    </button>

  </ion-content>
</ion-view>

controller.js

.controller('DashCtrl', function($scope) {

    $scope.input = {
        countNum: 1
    };

    $scope.create = function() {
        // Logic here
    };


})

count.html

<ion-view view-title="Count">

    <ion-nav-bar class="bar-energized">
        <ion-nav-back-button class="button-clear">
            <i class="ion-arrow-left-c"></i> Back
        </ion-nav-back-button>
    </ion-nav-bar>

  <ion-content class="padding">

    <button class="button button-full button-positive">
        ({{input.countNum}})
    </button>

  </ion-content>
</ion-view>

app.js

  .state('tab', {
    url: "/tab",
    abstract: true,
    templateUrl: "templates/tabs.html"
  })

  // Each tab has its own nav history stack:

  .state('tab.dash', {
    url: '/dash',
    views: {
      'tab-dash': {
        templateUrl: 'templates/tab-dash.html',
        controller: 'DashCtrl'
      }
    }
  })

  .state('tab.count', {
    url: '/count',
    views: {
      'tab-dash': {
        templateUrl: 'templates/count.html',
        controller: 'DashCtrl'
      }
    }
  })

页面之间不共享控制器 - 每次使用控制器时都会创建一个新实例。您也不应期望能够与该控制器范围之外的任何内容共享来自该控制器的数据。如果您需要在页面或控制器之间共享数据,您应该使用服务或 "value" 对象来维护该状态。另一种选择是使用状态参数在页面之间传递数据:

ui-sref="tab.count({ input: input })"

请注意,Ionic 使用 Angular UI Router 项目作为其导航逻辑,因此那里的文档也适用于使用 Ionic。