AngularJS中的服务变量未更新

时间:2015-04-13 02:01:53

标签: angularjs

我有一个变量workingIdx,需要更新为它被点击的div的id。它会更新,但是当我再次查询它时,它不会显示新值。

我的服务:

writingPage.service('Lctr', function() {

this.workingIdx = 0;
    return {
        getWorkingIdx: this.workingIdx,
        setWorkingIdx: function(i) {
            this.workingIdx = i;
            console.log("wIdx="+this.workingIdx);
        }
    };
});

我的控制器,我正在进行更新和检查...

writingPage.controller('DataController' , ['SnippetPojo','$scope', '$timeout', 'Lctr', function(SnippetPojo, $scope, $timeout, Lctr) {

$scope.currDispLine = '';
$scope.myId = -1;
    $scope.localCursor = 0;

$scope.hideOrShow = function(id, currentDivCursor) {
    if(id <= currentDivCursor)
    {
        console.log("wIdx="+Lctr.getWorkingIdx+ " id="+id);
        return false;
    }
    else
    {
        return true;
    }

}

$scope.click = function(id) {
            $scope.myId = id;
            Lctr.setWorkingIdx($scope.myId);
    console.log('MyId='+$scope.myId);
}

$('div').on( "keypress", function( event ) {
    console.log("Event="+event.keyCode + " : "+event.which);
    code = (event.keyCode ? event.keyCode : event.which);
    if ( (code == 37 || code == 39) && event.shiftKey == true) 
    {    
            $timeout(function() {console.log('Selection set= ' +window.getSelection()); return false;}, 2200);

    }
    if ( code == 13) {
                console.log("ENTERed ID="+$scope.myId + " wIdxOLD = "+ Lctr.getWorkingIdx);
        if(Lctr.getWorkingIdx == $scope.myId) {

            Lctr.setWorkingIdx(Number(Lctr.getWorkingIdx) +1);
            localCursor = (Number(Lctr.getWorkingIdx) +1);
            console.log("ENTERed ID="+$scope.myId + " wIdxNEW = "+ Lctr.getWorkingIdx);

            $('#'+$scope.myId).blur();
            $('#'+(Number(Lctr.getWorkingIdx) +1)).mousedown();

            return false;
        }
    }
});
}]);
}

最后是HTML

<div id='repeater' data-ng-controller='RepeatController'>
        <!--<data-ng-div-line data-ng-repeat="div in divs track by $index" id="{{$index}}"></data-ng-div-line>-->
        <div data-ng-repeat="div in divs track by $index" id="{{div}}" data-ng-controller='DataController' data-ng-click='click(div)' contenteditable="true" class="writediv" data-ng-model="localCursor" data-ng-mouseover="setId(div)" data-ng-show="!hideOrShow(div, localCursor)" data-ng-hide="hideOrShow(div, localCursor)"></div>
</div>  

当我点击DIV时,我看到wIdx = 1设置,然后当我在DIV中按Enter键时,显示输入的ID = 0 wIdxNEW = 0

1 个答案:

答案 0 :(得分:1)

尝试将此更改为自我...

writingPage.service('Lctr', function() {

var self = this;

self.workingIdx = 0;
    return {
        getWorkingIdx: self.workingIdx,
        setWorkingIdx: function(i) {
            self.workingIdx = i;
            console.log("wIdx="+self.workingIdx);
        }
    };
});

this在函数

中获取新值