在Angularjs一个奇怪的情况下

在Angularjs一个奇怪的情况下

本文介绍了为什么不将这些数据绑定?在Angularjs一个奇怪的情况下,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是控制器:

.controller('DataCtrl', function($ionicPlatform, $scope, $rootScope) {

    $ionicPlatform.ready(function(){
        $scope.analyticsOn = localStorage.analytics;
        console.log('analytics are', $scope.analyticsOn);

        $scope.counter = 0;
        $scope.change = function(){
            $scope.counter++;
            console.log('analytics are ' + $scope.analyticsOn);
            localStorage.analytics = $scope.analyticsOn;
        }
    })
});

这里是HTML:

And here is the html:

<li class="item item-toggle">
   <i class="icon ion-cloud"></i> Data Tracking is {{analyticsOn}} {{counter}}
      <label class="toggle toggle-balanced">
         <input type="checkbox" ng-model="analyticsOn" ng-change="change()">
          <div class="track">
             <div class="handle"></div>
          </div>
       </label>
    </li>

pressing切换获取控制台消息的分析是未定义不管是什么。

Pressing the toggle gets the console message "analytics are undefined" no matter what.

然而,这里是东西,在应用程序中的{{analyticsOn}}更新和翻转从真到假和{{柜台}}从零初始值计数。

Yet, and here is the thing, in the app the {{analyticsOn}} updates and flips from true to false and the {{counter}} counts up from an initial value of zero.

所以我知道 -


  • 一个。双向数据绑定工作,或者计数器是行不通的。

  • 乙。 analyticsOn正在发生变化。

那么为什么不console.logs表现出来?该计划是将值回localStorage.analytics数据持久性,但这是我第一次用NG-变化。如果我这样做的纯JavaScript这将是罚款。

So why don't the console.logs show it? The plan is to put the value back into the localStorage.analytics for data persistence but this is the first time I've used ng-change. If I did this in pure JavaScript it would be fine.

有人吗?

编辑:最后我放弃这是我听到ngStorage - 一个插件,可以让你直接绑定流入和流出的localStorage的没有得到从模型数据转换的localStorage的中间步骤

I ended up abandoning this as I heard about ngStorage - a plugin that lets you bind directly into and out of localStorage without the intermediate step of getting data from the model into localStorage.

这本身造就了它自己的问题,我会问过的问题。

That itself has brought up it's own issues, which I'll be asking questions about elsewhere.

推荐答案

这可能可以同时更新的localStorage &安培; $范围变量一起通过存储整个localStorage的一个范围变量,这样调整,你可以摆脱的NG-变化指令了。

It could possible to update both localStorage & $scope variable together by storing whole localStorage in one scope variable, By making this change you could get rid of ng-change directive too.

标记

<input type="checkbox" ng-model="localStorage.analyticsOn" ng-change="change()">

code

.controller('DataCtrl', function($ionicPlatform, $scope, $rootScope) {

    $ionicPlatform.ready(function(){
        $scope.localStorage= localStorage;
        console.log('analytics are', $scope.localStorage.analyticsOn);

        $scope.counter = 0;
        $scope.change = function(){
            $scope.counter++;
            console.log('analytics are ' + $scope.localStorage.analyticsOn);
        }
    })
});

这篇关于为什么不将这些数据绑定?在Angularjs一个奇怪的情况下,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 16:44