var vm = this,使$ http请求两次

时间:2017-04-22 10:12:44

标签: angularjs ionic-framework

这是我的控制器代码:

.controller('TransitCtrl', function ($ionicPlatform, $scope, $state, $q, $ionicSideMenuDelegate, $timeout, $http, design, config) {
    $ionicSideMenuDelegate.canDragContent(false);
    var vm = this;
    vm.userImg = design.user_img;

    vm.isGetStarted = false;
    vm.getPV = true;
    vm.getPL = false;
    vm.showWelcome = false;
    var counter = 1;
    $ionicPlatform.ready(function(){  
        $timeout( function(){
             var userDataStageFirst = {
              url: config.baseURL + 'userDataStageFirst',
              dataServer: {
                serverTaskRequest: counter
              }
            }
            var url = userDataStageFirst.url;
            var dataServer = userDataStageFirst.dataServer;
            $http.post(url, dataServer).success(function (data, status, headers, config) {
                alert(data)
              })
              .error(function () {
                alert("error");
              });
        }, 1000 ); 
     });
  })

这是这个app.js

.state('app.transit', {
      url: '/transit',
      views: {
        'menuContent': {
          templateUrl: 'templates/transit.html',
          controller: 'TransitCtrl'
        }
      }
    })

和我的html页面

<ion-view hide-nav-bar="true" ng-controller="TransitCtrl as vm">
  <ion-content>
      hello world
  </ion-content>
</ion-view>

当我使用$scope代替vm时,它的效果非常好,但当我使用vm时,它会向服务器发送2 $http个请求。在这里无法理解this概念。

1 个答案:

答案 0 :(得分:2)

尝试从模板中删除ng-controller="TransitCtrl as vm"

并更改为此

state('app.transit', {
  url: '/transit',
  views: {
    'menuContent': {
      templateUrl: 'templates/transit.html',
      controller: 'TransitCtrl as vm'
    }
  }
})