【发布时间】:2016-01-23 07:48:09
【问题描述】:
我正在尝试根据控制器中变量的值使用不同的templateUrl,但我无法绑定这些变量。我一直在尝试在链接功能中执行此操作,不确定是否有更简单的方法。首先,这是我的 HTML:
<div po-generic-notification title='errorModal.title' error-list="errorModal.errorList" type="mostRecentError.type" message="mostRecentError.message" error="mostRecentError.message"></div>
这会触发以下指令(在此阶段正在进行一些工作......):
.directive('poGenericNotification', function($compile) {
var openFuncNameErm = 'openErm';
return {
controller: 'ErmModalCtrl',
restrict: 'EA',
scope: {
title: '=',
errorList: '=',
type: '=',
message: '='
},
transclude: true,
link: function(scope, element, attrs) {
console.log(attrs.type);
if (attrs.type==="Alert") {
templateUrl: 'src/alerts/templates/error-alert.html';
error: attrs.message;
}
else if (attrs.type==="Info") {
templateUrl: 'src/alerts/templates/info-alert.html';
info: attrs.message;
}
error: attrs.message; //temporary
element.removeAttr('po-generic-notification'); // necessary to avoid infinite compile loop
var ngClick;
if (attrs.before) {
ngClick = attrs.ngClick ? openFuncNameErm + '()' + '; ' + attrs.ngClick : openFuncNameErm + '()';
}
else {
ngClick = attrs.ngClick ? attrs.ngClick + '; ' + openFuncNameErm + '()' : openFuncNameErm + '()';
}
element.attr('ng-click', ngClick);
$compile(element[0])(scope);
}
}
})
您可以在我的链接函数中看到我尝试根据attrs.type 的值有条件地设置templateUrl。 console.log 的结果是 mostRecentError.type 而不是来自控制器的值。这是我的控制器:
.controller('ErrorModalCtrl', ['errorHandler', '$scope', function (errorHandler, $scope) {
$scope.errorModal = {
title: 'Notification Centre',
errorList: []
};
$scope.mostRecentError = {
type:'', message: '', timestamp: ''
};
$scope.addError = function(type, message) {
errorHandler.addError(type, message);
$scope.mostRecentError = errorHandler[0];
};
$scope.errorModal.errorList = errorHandler;
}]);
这是正确的方法吗?为什么我的 attrs.type 值是文字,而不是对控制器的引用?
谢谢
【问题讨论】:
-
属性总是被读取为文字,而不是将它们传递到从父作用域评估它们的作用域
标签: angularjs angularjs-directive binding