下面是我用的,在這裏我想基於工場的變量更新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;
})
我想能夠添加/刪除其他控制器的錯誤,並讓它更新指令。目前,對於初始值$watch
mostRecentError
回調是undefined
,那麼它永遠不會更新。我錯過了什麼?
我實際上已經嘗試過兩種方法,都沒有成功。編輯了這個問題。謝謝。 – MDalt
......我糾正了。其他地方有一個錯誤隱藏了這個......好的一個。 – MDalt
@MDalt很好,很高興它解決了。 –