Get state of toggled element

时间:2015-11-12 11:41:06

标签: javascript toggle angular-ui

I am building an application with angularui. I have a a span that contains an image that I need to toggle on and off and save the state on when user hits save. How do I get the toggle state of this element?

Here's my code:

<div class="scrollable" ng-controller="UpdateProspectCtrl">
<div class="scrollable-content section">
    <form role="form" ng-submit='updateProspect()'>
        <fieldset>
            <p ui-state="pinProspect" ng-model="pinprospectpara"
               ui-class="{'text-primary': pinProspect}"
               class="text-default">

                <span ng-model="pinprospect" style="font-size: 40px; display: block;"
                   class="fa fa-paperclip" ui-toggle='pinProspect'
                   ui-class="{'active': pinProspect}" ng-click="setPinned()"></span>
            </p>
        </fieldset><hr>
        <button class="btn btn-primary btn-block">
            Save
        </button>
    </form>
</div>

Controller:

angular.module('Main', [
      'mobile-angular-ui.core.sharedState'])
    .controller('UpdateProspectCtrl', function($scope){
      // set the state here on click of the toggelable span.
      $scope.setPinned = function() {
        $scope.updateProspectPinned = !$scope.updateProspectPinned;
        console.log("setting pinned to", $scope.updateProspectPinned);
      };

      // Using the above function I am able to guage the state. However, next time when I load this page I want to set the last state. If the user had selected it, I want to show it as selected. How do I achieve this behavior?
    })

Also, even though I have given it an ng-model I am unable to access it in my controller. I can access all the remaining elements of the page except for this span and its container p tags. What could be the issue?

1 个答案:

答案 0 :(得分:0)

你不应该将ng-model指令绑定到除输入和textareas之外的任何其他内容,如果你想显示模型使用,它不适用于跨度 -  {{updateProspectPin}}

ng-click指令应该是负责切换值的指令。

如果你想保存状态,你应该打开一个单身的角度服务,并将保存的状态存储在那里。

新服务 -

function pinnedStateService (localStorageService) {
    var service = this;

    service.pinState = { value: getPinStateFromLocalStorage()}; 

    service.toggleState = function () {
      service.pinState.value = !service.pinState.value;
      localStorageService.set("pinItem", this.pinState.value);// i am not sure this is the correct syntax
    }

    function getPinStateFromLocalStorage() {
        return localStorageService.get("pinItem"); // i am not sure this is the correct syntax
    }
}

function controller(pinnedStateService){
  $scope.pinState = pinnedStateService.pinState;
  $scope.toggleState = pinnedStateService.toggleState; // binding function to scope so you can use it on the view
}

在视图中 -

 <element ui-class="{'active': pinState}" />
祝你好运