在两个视图中使用Angular JS的Ionic App的动态列表

时间:2015-09-09 16:12:53

标签: javascript angularjs ionic-framework

我有一个带有Angular JS的Ionic应用程序。我有一个动态复选框列表,从app.js中的数组调用。我有它,以便当用户点击一个复选框时,上面的列表会根据他们的选择进行更新,我想要的是选择放入另一个视图而不是另一个div,即选项卡1 = List,tab - 2 = =。代码是:

  $scope.myList = [
      {name:'Choice one'},
      {name:'Choice two)'}
  ];

  $scope.myChoices = [];


  $scope.stateChanged = function(checked,indx){
    var item = $scope.myList[indx];
    if(checked){
        $scope.myChoices.push(item);
    }else{
        var index = $scope.myChoices.indexOf(item);
        $scope.myChoices.splice(index,1);
    }
}

HTML:

<div>
  <div class="item item-dark item-icon-right">
   My Choices
  </div>

  <ul class="list" >
    <li class="item" ng-repeat='item in myChoices'>
       <p>{{item.name}}</p>

    </li>
    </ul>
    <div class="item item-dark item-icon-right">
     University list
    </div>
    <div class="item item-input-inset">
     <label class="item-input-wrapper">
       <i class="icon ion-ios-search placeholder-icon"></i>
       <input type="text" placeholder="Search" ng-model="search">
     </label>
     <button class="button ion-close-circled input-button button-small"
               ng-click="search = ''" ng-show="search.length">
               Clear search
             </button>

   </div>
  <ul class="list" >
    <li class="item item-checkbox" ng-repeat='item in myList | filter: search'>
  <label class="checkbox">
   <input type="checkbox" ng-model="checked" ng-change='stateChanged(checked,$index)'>
  </label>
      <p>{{item.name}}</p>

    </li>
    </ul>
</div>

标签:

<ion-tabs class="tabs-icon-top tabs-dark">

    <ion-tab title ="List" icon-on="home" icon-off="home"  href="#/tab/list">
    <ion-nav-view name="list-tab"></ion-nav-view></ion-tab>


    <ion-tab title ="My choices" icon-on="choices" icon-off="choices" href="#/tab/choice">
    <ion-nav-view name="choice-tab"></ion-nav-view></ion-tab>


</ion-tabs>

1 个答案:

答案 0 :(得分:1)

当您尝试跨多个视图发送数据时,最简单的方法是将数据存储在工厂变量中。无论何时需要数据,您都可以通过简单的获取从工厂获得数据。

// This module can be in its own javascript file
angular.module('choicesFactory', [])
.factory('choicesFactory', function() {
    var choicesStored = [];
    return {
        storeChoices: function(choices) {
           choicesStored = choices;
           return;
        },
        getChoices: function() {
           return choicesStored;
        },
    };
});

现在,要实现这段代码,您需要做的就是在index.html中包含angularjs之后包含javascript文件,并将choicesFactory添加到您的应用程序依赖项中。

当您从控制器调用该功能时,您可以说:

.controller('choicesController', [
    '$scope',
    '$state',
    'choicesFactory'
    function($scope, $state, choicesFactory) {
        // An example with getting the choices
        var choices = choicesFactory.getChoices()
}]);

如果这没有多大意义,我制作了一个codepen示例应用程序,演示了所有部分协同工作。

Click here to check out the example. :) Happy coding