2016-07-01 38 views
2

發現了幾個人有類似的問題,但通常的作用域。$ apply不適用於我($ digest已在進行中)。今天讓我感動。

請在下面找到我的指令的簡化版本。

  1. initialize()將myValue設置爲其初始值。
  2. $ rootScope事件被捕獲。
  3. 承諾正在解決。
  4. $ localStorage更新
  5. console.log(myValue)提供正確的值。

但是我的視圖未更新。這是怎麼回事?!

(function() { 
 
    'use strict'; 
 

 
    angular 
 
    .module('myApp') 
 
    .directive('myDirective', myDirective); 
 

 
    function myDirective($rootScope, $localStorage, MyPromise, MyService) { 
 
    var linkFunction = function (scope, element, attributes) { 
 

 
     scope.myValue = null; 
 

 
     $rootScope.$on('someEvent', function (event, data) { 
 

 
     MyPromise().get({}, function (result) { 
 
      $localStorage.result = result; 
 
      scope.myValue = MyService.getFromLocalStorageAndReturnStuff(); 
 
      console.log(scope.myValue); 
 
     }); 
 
     }); 
 

 
     initialize(); 
 

 
     function initialize() { 
 

 
     scope.myValue = MyService.getFromLocalStorageAndReturnStuff(); 
 

 
     } 
 
    }; 
 

 

 
    return { 
 
     restrict: 'A', 
 
     transclude: true, 
 
     replace: true, 
 
     scope: { 
 
     someProperty: '=myProperty' 
 
     }, 
 
     link: linkFunction, 
 
     templateUrl: 'myTemplate.html' 
 
    }; 
 
    } 
 
})();
{{myValue}}

+0

嘗試清除緩存 –

回答

0

什麼工作對我來說,我有一個外部作用域屬性(scope.someProperty),當我的事件發生時它也在改變。

看着它確實會改變視圖中反映的範圍。

我知道這不是一個完美的解決方案,如果真的必須對某些事件做出反應,但我想提供我的解決方案以防萬一它可能對其他人有幫助。

如果有人能夠提供真實問題的答案,我很樂意接受他的回答。

(function() { 
 
    'use strict'; 
 

 
    angular 
 
    .module('myApp') 
 
    .directive('myDirective', myDirective); 
 

 
    function myDirective($rootScope, $localStorage, MyPromise, MyService) { 
 
    var linkFunction = function (scope, element, attributes) { 
 

 
     scope.myValue = null; 
 

 
     scope.$watch('someProperty', function(newVal){ 
 
     
 
     if(newVal!==null){ 
 
      MyPromise().get({}, function (result) { 
 
      $localStorage.result = result; 
 
      scope.myValue = MyService.getFromLocalStorageAndReturnStuff(); 
 
      }); 
 
     } 
 
     
 
     }); 
 
     
 
     initialize(); 
 

 
     function initialize() { 
 

 
     } 
 
    }; 
 

 

 
    return { 
 
     restrict: 'A', 
 
     transclude: true, 
 
     replace: true, 
 
     scope: { 
 
     someProperty: '=myProperty' 
 
     }, 
 
     link: linkFunction, 
 
     templateUrl: 'myTemplate.html' 
 
    }; 
 
    } 
 
})();

0

Link功能不看模式的轉變,因此做變量applyAsync函數內部設置

scope.$applyAsync(function(){ 
//set here 
}); 
+0

試圖打電話 'scope.myValue = MyService.getFromLocalStorageAndReturnStuff();'在$ applyAsync中。沒有影響,既不例外,也不改變觀點。 – LBA

+0

嘗試調用範圍。$應用後設置,刪除applyAsync,也嘗試不隔離範圍 –

+0

謝謝,但看到我的評論,我已經嘗試範圍。$應用 - 但我已經在一個摘要週期。 – LBA

相關問題