2015-10-19 110 views
0

我試圖用一個控制器構建一個指令,該控制器更新一個ViewModel變量並調用回調函數。在回調函數中應該使用更新後的變量,但它仍然具有舊值。AngularJS:在指令控制器的回調中使用ViewModel變量

HTML:

<div ng-app="app" ng-controller="AppCtrl"> 
    Var: {{vm.var}} 
    <ng-element var="vm.var" func="vm.func()"></ng-element> 
</div> 

的JavaScript:

var app = angular.module('app', []); 

app.controller('AppCtrl', function($scope) { 
    $scope.vm = { 
     var: 'One', 
     func: function() { 
      alert($scope.vm.var); 
     } 
    }; 
}); 

app.directive('ngElement', function(){ 
    return { 
     restrict: 'E', 
     scope: true, 
     bindToController: { 
      var: '=', 
      func: '&' 
     }, 
     controllerAs: 'ctrl', 
     replace: true, 
     template: '<button ng-click="ctrl.doIt()">Do it</button>', 
     controller: function() { 
      this.doIt = function() { 
       this.var = 'Two'; 
       this.func(); 
      }; 
     } 
    }; 
}); 

所以點擊該按鈕時,doIt方法() IST調用,更新VAR,並呼籲FUNC()。但是當執行func()時,var仍舊得到舊值「One」。執行後,ViewModel被更新,值爲「Two」。

有沒有什麼辦法可以在執行該函數之前更新ViewModel?

JSFiddle

回答

0

不知道到底是什麼你的指令做,因爲我從來沒有使用過bindToController,但這似乎工作:

directive('ngElement', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      var: '=', 
      func: '&' 
     }, 
     replace: true, 
     template: '<button ng-click="doIt()">Do it</button>', 
     controller: ['$scope', '$timeout', function($scope, $timeout) { 
      $scope.doIt = function() { 
       $scope.var = 'Two'; 
       $timeout(function() { 
        $scope.func(); 
       }); 
      }; 
     }] 
    }; 
}); 
相關問題