2015-07-02 48 views
0

Angularjs控制器功能我有一個創建它的孤立範圍屬性,並回調函數AngularJs指令:傳遞參數,從指令

.directive('testButton', [function() { 
    return { 
    restrict: 'A', 
    controller: 'TestDirectiveController as vmDirective', 
    scope: {  
     myCallBack:'&myCallBack', 
     myVariable: '=myVariable' 
    }, 
    template: function (element, attrs) { 
     return '<button data-ng-click="vmDirective.onButtonClicked(2)">Set myVariable = 2</button>'; 
    } 
};}]) 

在指令按鈕被點擊並執行onButtonClicked功能。然後設置一個範圍變量並調用$scope.myCallBack函數。

回調函數被執行並執行以下操作: console.log($scope.linkedVariable);

問題是$scope.linkedVariable尚未更新,在那個階段的$scope.linkedVariable仍然是以前的值。

當我包裹在setTimeout上面的代碼正確的值被檢索:setTimeout(function(){console.log($scope.linkedVariable)}, 2000);

我的問題是,如何將正確的值傳遞給onCallBack功能。

請參見下面的完整代碼示例:

angular.module('application',[]) 

    .directive('testButton', [function() { 
     return { 
     restrict: 'A', 
     controller: 'TestDirectiveController as vmDirective', 
     scope: {  
       myCallBack:'&myCallBack', 
       myVariable: '=myVariable' 
     }, 
     template: function (element, attrs) { 
      return '<button data-ng-click="vmDirective.onButtonClicked(2)">Set myVariable = 2</button>'; 
     } 
     }; 
    }]) 

    .controller("TestDirectiveController", ['$scope', function($scope){ 
     var self = this; 
     self.onButtonClicked = function(value){ 
      $scope.myVariable = value; 
      $scope.myCallBack(); 
     }; 
    }]) 

    .controller("TestController", ['$scope', function($scope){ 
     var self = this; 
     $scope.linkedVariable = null; 

     self.onCallBack = function(){ 
     console.log($scope.linkedVariable); 
     setTimeout(function(){console.log($scope.linkedVariable)}, 2000); 
    }; 
}]) 

HTML:

<div data-ng-controller="TestController as vm"> 
    <div data-test-button="" data-my-call-back="vm.onCallBack()" data-my-variable="linkedVariable"></div> 
</div> 

的jsfiddle:http://jsfiddle.net/ff5ck0da/1/

回答

2

由於http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters,我找到了一種更可接受/正確的方法來克服我的問題。

而不是訪問控制器中的$scope.linkedVariable,我現在接受該值作爲該函數的參數。

爲了得到這個工作,我不得不在HTML改變函數聲明:

data-my-call-back="vm.onCallBack"

控制器函數聲明:

self.onCallBack = function(myVariable){ 
    console.log(myVariable);   
}; 

指令就可以調用的功能等:

self.onButtonClicked = function(value){   
    $scope.myCallBack()(value); 
}; 

請s ee更新JSFiddle:http://jsfiddle.net/ff5ck0da/9/

0

您可以將setTimeout的甚至改變

setTimeout(function(){console.log($scope.linkedVariable)}, 0); 

這會將變量的分辨率推到異步堆棧的底部。 因而角消化循環完成後(在本質上是變量值設定)評估

如果你不想使用的setTimeout您可以使用此:

self.onCallBack = function(){ 
     var accessor = $parse($scope.linkedVariable); 
     $scope.value = angular.copy(accessor($scope.$parent)); 
     console.log($scope.linkedVariable); 
}; 

在這裏,你基本上是告訴角度來不使用副本,而是使用實際的父變量。

+0

我不想使用'setTimeout',因爲它似乎有點哈克。 –

+0

@TjaartvanderWalt我同意看到我的更新回答 –

+0

這似乎有點細緻的東西如此微不足道?沒有更多內置的方式嗎? –