2015-07-02 25 views
1

我有這個指令,我試圖讓它重新加載它自動獲取的內容。到目前爲止,沒有太多的運氣。小心幫忙?該指令永不重新加載其內容

編輯:我已經嘗試了建議的答案,但它不會工作。我得到一個$ digestx10錯誤。

一切工作正常,並保存好,DOM只是不會重新加載。

angular.module('mymodule').directive('chatContent', 
    ["$compile",'localStorageService','loginService','peopleOnlineService', 
    function($compile, localStorageService, loginService, peopleOnlineService) { 


var LoadData = function (data, userId) { 
    var template = ''; 
    //localStorageService.IsUser(data.userId); 

    if(localStorageService.IsUser(userId) === true){ 
     template = '<div class="feedItemChat"><div class="chatItem"><div class="chatMessage userChatMessage">{{content.chatMessage}}</div></div></div>'; 
    }else{ 
     template = '<div class="feedItemChat"><div class="chatItem"><div class="chatMessage otherChatMessage">{{content.chatMessage}}</div></div></div>'; 
    } 
    return template; 
}; 

var linker = function (scope, element) { 

    var data = localStorageService.LoadDataLocal(localStorageService.CheckCorrectRoom(loginService.GetUser().userId, peopleOnlineService.GetParams().userId)); 

    scope.$watch(data, function(){ 
     element.html(LoadData(data,scope.content.userId)).show(); 
     $compile(element.contents())(scope); 
    }); 
}; 

return { 
    restrict: 'E', 
    link: linker, 
    scope: { 
     content: '=' 
    } 
}; 
}]); 

我也想知道,如何在這裏插入html模板,而不是愚蠢的長字符串呢?

+1

那麼你只設置可變數據一次,難怪它不會改變。將'LoadDataLocal ...'調用放入一個函數中,並將該函數用作手錶的第一個參數(所以當注入新的東西時你會注意到)。 – doldt

+0

小心寫下它?我在嘗試,但它不起作用... –

+0

嘗試用第三個參數「true」調用'$ watch'。 (第三個參數是'objectEquality') –

回答

1

取這與大量的鹽,因爲我是一個菜鳥,可能缺少的東西...

我懷疑你正在修復這個錯誤的地方。 scope.content(在外部範圍內)是否設置在Angular框架的外部?如果是這樣,請將scope.content =...包裝在$ scope中。$ apply()使框架觸發任何手錶。

我想你根本不需要$ watch。當您需要觸發的更改未被視圖引用時,您只需使用$ watch。每個{}表達式創建一個表表達式

考慮在指令上使用單個模板,並在模板中的ng-class='...'中包含「chatMessageClass」範圍值。

這最大限度地減少了你和瀏覽器的工作。除非代碼的其他部分有一些不明顯的副作用,否則一切都會消失。

var linker = function (scope, element) { 
    scope.chatMessageClass = localStorageService.IsUser(scope.content.userId) ? 
     'userChatMessage' : 'otherChatMessage'; 
}; 

參考文獻: https://stackoverflow.com/a/15113029/685923 https://docs.angularjs.org/api/ng/directive/ngClass https://docs.angularjs.org/api/ng/type/ $ rootScope.Scope#$適用

1

注意:我沒有解決DOM再生的問題,只是不正確的$ watch設置。按照Petr Averyanov的評論,要修復摘要問題,請使用具有模板屬性的常規指令。

相反的:

var data = localStorageService.LoadDataLocal(localStorageService.CheckCorrectRoom(loginService.GetUser().userId, peopleOnlineService.GetParams().userId)); 

scope.$watch(data, function(){ 
    /* ... */ 
}); 

嘗試:

scope.$watch(
    function(){ 
     return localStorageService.LoadDataLocal(localStorageService.CheckCorrectRoom(loginService.GetUser().userId, peopleOnlineService.GetParams().userId)); 
    }, 
    function(newData){ 
     /* this code will run when LoadDataLocal returns a different value*/ 
    }); 

(請注意,我消除了data變量,而是使用$在LoadData觀看NEWVALUE)

+0

它告訴我我達到了10次摘要迭代。谷歌搜索... –

+0

仍然有這個錯誤!有任何想法嗎? –

+0

你確定你需要使用compile嗎? (我剛剛複製了該部分)請參閱Petr Averyanov對您的OP的評論 – doldt