下面是我用的,在这里我想基于工场的变量更新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很好,很高兴它解决了。 –