2015-11-03 37 views
0

下面是我用的,在這裏我想基於工場的變量更新template URL一個指令:

.directive('poGenericNotification',['errorHandler', function(errorHandler) { 
return { 
    controller: 'ErmModalCtrl', 
    restrict: 'EA', 
    scope: { 
    title: '=', 
    errorList: '=', 
    errMsg: '=', 
    error: '=', 
    info: '=', 
    numNotifications: '=', 
    messageOverflow: '=' 
    }, 
    template: "<div ng-include='getTemplateUrl()' class='generic-notif-container' ng-click='openErm()'></div>", 
    transclude: true, 
    link: function(scope) { 
    scope.$watch(errorHandler.getMostRecentError(), function(mostRecentError) { 
     scope.getTemplateUrl = function() { 
     if (mostRecentError.type === "Alert") { 
      return 'src/alerts/templates/error-alert.html'; 
     } 
     else if (mostRecentError.type === "Info") { 
      return 'src/alerts/templates/info-alert.html'; 
     } 
     } 
    }, true); 
    } 
    } 
}]) 

這裏是它參考的工廠:

.factory('errorHandler', function() { 
var errorArray = []; 
var mostRecentError = { 
    type:'', message: '', timestamp: '' 
}; 
function compareObjs(a,b) { 
    //sorting function 
} 
errorArray.addError = (function (type, message) { 
    var timestamp = Date.now(); 
    errorArray.push({type: type, message: message, timestamp: timestamp}); 
    errorArray.sort(compareObjs); 
    errorArray.generateMostRecentError(); 
}); 
//....some functions 
errorArray.generateMostRecentError = function() { 
    if (errorArray[0].message.length > 138) { 
    mostRecentError.message = errorArray[0].message.slice(0, 138) + "..."; 
    messageOverflow = true; 
    } else { 
    mostRecentError.message = errorArray[0].message; 
    messageOverflow = false; 
    } 
    mostRecentError.type = errorArray[0].type; 
    mostRecentError.timestamp = errorArray[0].timestamp; 
    console.log(mostRecentError); 
} 
errorArray.getMostRecentError = function() { 
    console.log(mostRecentError); 
    return mostRecentError; 
} 
return errorArray; 
}) 

我想能夠添加/刪除其他控制器的錯誤,並讓它更新指令。目前,對於初始值$watchmostRecentError回調是undefined,那麼它永遠不會更新。我錯過了什麼?

回答

1

您需要將該函數傳遞給$watch而不是其結果。改爲:

scope.$watch(errorHandler.getMostRecentError, ...);

+0

我實際上已經嘗試過兩種方法,都沒有成功。編輯了這個問題。謝謝。 – MDalt

+0

......我糾正了。其他地方有一個錯誤隱藏了這個......好的一個。 – MDalt

+0

@MDalt很好,很高興它解決了。 –

1

要讓呼籲每個消化循環的功能,您應該

errorHandler.getMostRecentError 

更換

errorHandler.getMostRecentError() 

否則你是看連接到該指令的範圍函數調用作爲變量的結果。