繁体   English   中英

使用controllerAs在Angular控制器中应用范围更改

[英]Apply scope change in Angular controller using controllerAs

我有一个看起来像这样的控制器:

angular
  .module('app.core')
  .controller('TestController', TestController);

TestController.$inject = ['$timeout', '$interval'];

function TestController($timeout, $interval) {

  var vm = this;
  vm.formHeight = '0px';

  $timeout(function() {
    var heightCheck = $interval(function() {
      var formHeightNew = document.getElementById('form').offsetHeight;
      vm.formHeight = formHeightNew + 'px';
    }, 500);
  }, 2000);

};

因此,间隔在2000毫秒(超时)之后开始,然后每500毫秒运行一次。 每次迭代都会用新值更新视图模型。 html视图中的变量似乎没有更新。 如何应用更新?

我试过添加vm.$apply()并注入$ scope,然后使用$scope.$apply()但似乎都不起作用。

html只是像这样使用ngStyle的变量(注意controllerAs值是test):

<div class="form-wrapper" ng-style="{'height': test.formHeight}">
</div>

初始绑定值“ 0px”有效,但更新无效。

尝试这个

angular
  .module('app.core')
  .controller('TestController', TestController);

TestController.$inject = ['$scope', '$timeout', '$interval'];

function TestController($scope, $timeout, $interval) {

  $scope.formHeight = '0px';

  $timeout(function() {
    var heightCheck = $interval(function() {
      var formHeightNew = document.getElementById('form').offsetHeight;
      $scope.formHeight = formHeightNew + 'px';
    }, 500);
  }, 2000);

};

和HTML

<div class="form-wrapper" ng-style="{'height': formHeight}">
</div>
This piece of code works properly update every half of second and add new height: 

    <div class="testCtrl" data-ng-controller="appController as test">
        <form action="state1_submit" id="form" method="get" accept-charset="utf-8" >
            <input type="text" name="" value="" >
            <div class="form-wrapper" ng-style="{'height': test.formHeight}">
            </div>
        </form>
    </div>

angular.module('myApp')
    .controller('appController', appController);

function appController($timeout, $interval) {
    var vm = this;
    vm.formHeight = '0px';
    $timeout(function() {
        var heightCheck = $interval(function() {
            var formHeightNew = document.getElementById('form').offsetHeight;
            vm.formHeight = formHeightNew + 'px';
            console.log(vm.formHeight);
            console.log('updat3e');
        }, 500);
    }, 2000);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM