2013-11-21 42 views
0

在我的角度指令,在回調,我打電話給$apply

  1. $scope.model.something
  2. 調用$scope.onAction()它採用model.something

我這樣做是一個$apply電話,但在被調用onAction()時間,model.something仍然是不確定的。

與此同時,$ apply後,{{model.something}}有一個正確的值,所以model.something被正確更新。

我想要設置model.something,所以我可以在onAction()中使用它。如何修復下面的代碼?

這裏的指令(我跳過不相關的代碼):

.directive(function() { 
    return { 
    scope: { 
     ngModel: '=', 
     onAction: '=' 
    }, 
    compile: function (element, attrs) { 
     return function (scope) { 
     // This is some callback which is invoked 
     // outside of digest cycle. 
     function callback() { 
      // Here I want to set model and call onAction callback 
      scope.$apply(function() { 
      scope.ngModel = 'something'; 
      scope.onAction(); 
      }); 
     } 
     } 
    } 
    }; 
}) 

與此同時,我的控制器看起來像:

var MyController = function ($scope) { 
    $scope.model = {}; 

    $scope.onAction = function() { 
    // Here I want $scope.model.something to be set to "something" 
    // But it's undefined. 
    alert($scope.model.something); 
    }; 
} 

最後,HTML:

<div ng-controller="MyController"> 
    {{ model.something }} 
    <my-directive ng-model="model.something" on-action="onAction"/> 
</div> 

還有一件事,我知道我可以撥打scope.onAction('something'),我正在尋找其他解決方案。

這是the fiddle

+0

我不認爲你已經鏈接到相關的小提琴。 – AlwaysALearner

+0

@CodeHater - 對,謝謝 - 現在鏈接有效。 – kamituel

回答

1

你可以簡單地包裹每行到它自己的應用$回調:

compile: function (element, attrs, transclude) { 
    return function (scope, element, attrs) { 
    setTimeout(function() { 
     var something = 'lorem ipsum'; 
     scope.$apply(function() { 
     scope.ngModel = something; 
     }); 
     scope.$apply(function() { 
     scope.onAction(); 
     }); 
    }, 200); 
    }; 
} 

Fiddle

+0

謝謝。這真的是解決這個問題的正確途徑嗎? – kamituel

+0

正確的方法是使用ngModelController與ngModel指令進行通信,並使用$ watch觀察模型上的更改:[Fiddle](http://jsfiddle.net/6Ar8D/)。 – Stewie

1

使用$timeout

$timeout(function(){ 
    scope.onAction(something); 
}); 

或者使用$watch

scope.$watch("ngModel",function(){ 
    scope.onAction(something); 
});