2013-10-19 26 views
1

我的內容中有一個代碼片段,它是從http獲取的模型。我使用語法高亮顯示來美化代碼。所以我需要在DOM爲該特定模型更新後立即調用JavaScript函數。模型的DOM顯示在視圖中後執行任務

下面是一個示例代碼,以清除它。我正在使用警報來演示它。在我的項目中,我會使用第三方插件來查找匹配的dom元素並對它們進行改造。 這裏, 我想顯示的列表後

的jsfiddle發生警報: http://jsfiddle.net/7xZde/2/

我的控制器有這樣的事情。

$scope.items = Model.notes(); 
alert('test'); 

即使在顯示項目列表之前還有警報,我希望顯示列表之後。

任何提示,以幫助我實現這一點。

+0

請把一些代碼 –

+0

更新。抱歉。我覺得這是愚蠢的懷疑,所以不想增加很多細節。 – Skeptor

回答

1

我們需要使用$超時,

$scope.items = Model.notes(); 
$timeout(function() { 
    alert('test'); 
}) 

啊這是愚蠢的,$超時似乎是用詞不當給我。我是2天齡的人。對不起,浪費你的時間。

0

對你來說幸運,我想做同樣的事情。突變觀察者是前進的道路,但是如果您需要與舊版瀏覽器的向後兼容性,則需要比這更多的代碼。

Working plunker適用於Firefox,Chrome和Safari。

的Javascript:

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

.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
}) 

.directive('watchChanges', function ($parse, $timeout) { 
    return function (scope, element, attrs) { 
     var setter = $parse(attrs.watchChanges).assign; 

     // create an observer instance 
     var observer = new MutationObserver(function (mutations) { 
      mutations.forEach(function (mutation) { 
       $timeout(function() { 
        var text = angular.element('<div></div>').text(element.html()).text(); 
        setter(scope, text); 
       }); 
      }); 
     }); 

     // configuration of the observer: 
     var config = { 
      attributes: true, 
      childList: true, 
      characterData: true, 
      subtree: true 
     }; 

     // pass in the target node, as well as the observer options 
     observer.observe(element[0], config); 
    }; 
}); 

HTML:

<body ng-controller="MainCtrl"> 
    <div watch-changes="text"> 
     <p>Hello {{ name }}</p> 
     <label>Name</label> 
     <input type="text" ng-model="name" /> 
    </div> 
    <pre>{{text}}</pre> 
    </body> 
+0

可以請你再看看我的問題,我用一個例子更新了它。它比你解釋的更糟糕。感謝你的付出。 – Skeptor

相關問題