У меня есть всплывающее окно, в котором я хочу отобразить шаблон на основе того, что выбирает пользователь.
<misc-Modal visible = "showMiscModal" template = "{{selectedTemplate}}">
Вот пример шаблона (CustomerContact.html):
<div class = "modal fade">
<div class = "modal-dialog my-order-grid-dialog">
<div class = "modal-content">
<div class = "modal-header">
<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">×</button>
</div>
<div class = "modal-body">
<span>this is the Customer Contact template</span>
</div>
</div>
</div>
Вот одна из функций, запускающих модальное окно:
$scope.showCustomerContact = function() {
alert("showing customer contact");
$scope.selectedTemplate = "/desktopmodules/mvc/TechSheetMaint/AngularTemplates/CustomerContact.html";
$rootScope.showMiscModal = true;
};
Я пытаюсь сделать это с помощью директивы:
angular.module("aps").directive("pmodal",
function() {
return {
restrict: "E",
transclude: true,
replace: true,
scope: true,
templateUrl: scope.selectedTemplate,
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible,
function(value) {
if (value === true)
$(element).modal("show");
else
$(element).modal("hide");
});
$(element).on("shown.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on("hidden.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
$scope.showPdfModal=false;
});
});
}
};
});
Я либо получаю
ReferenceError: scope is not defined
или
Error: [$http:badreq] http://errors.angularjs.org/1.7.0/$http/badreq?p0=undefined" when the page gets loaded.
Я также попробовал предложения в этом посте: Angular.js директива динамический templateURL
<misc-Modal visible = "$root.showMiscModal" template-url = "selectedTemplate">
angular.module("aps").directive("miscModal",
function() {
return {
restrict: "E",
templateUrl: function(elem, attrs) {
return attrs.templateUrl || "some/path/default.html";
},
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible,
function(value) {
if (value === true)
$(element).modal("show");
else
$(element).modal("hide");
});
$(element).on("shown.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on("hidden.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
$rootScope.showMiscModal = false;
});
});
}
};
});
но я просто получаю эту ошибку при загрузке страницы:
Error: [$templateRequest:tpload] http://errors.angularjs.org/1.7.0/$templateRequest/tpload?p0=%7B%7BselectedTemplate%7D%7D&p1=404&p2=Not%20Found
Как мне динамически изменять templateUrl в зависимости от того, какой шаблон я хочу отобразить? Я уже просмотрел другие примеры, и, похоже, они мне не подходят.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Ага. После долгих проб и ошибок:
<dmodal visible = "$root.showMiscModal">
</dmodal>
Файл шаблона:
<style>
@media (min-width: 768px) {
.modal-dialog {
width: 800px !important;
margin: 30px auto;
}
}
<span>this is the Status Changes template test4</span>
<div><span style = "float:left;width:150px">Name</span> <span style = "float:left; width:150px">Date</span> <span style = "float: left; width:50px">Old</span> <span style = "float: left; width:50px">New</span> Note</div>
<div ng-repeat = "s in statusChanges">
<span style = "float:left;width:150px">{{s.Name}}</span> <span style = "float:left; width:150px">{{s.ChangeDate|date:"MM/dd/yyyy HH:mm"}} </span> <span style = "float: left; width:50px">{{s.OldStatus}}</span> <span style = "float: left; width:50px">{{s.NewStatus}}</span> {{s.Note}}
</div>
Директива:
angular.module("aps").directive("dmodal",
function($rootScope) {
return {
template:'<div class = "modal fade">' +
'<div class = "modal-dialog">' +
'<div class = "modal-content">' +
'<div class = "modal-header">' +
'<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">×</button>' +
"</div>" +
'<div class = "modal-body" ng-include = "selectedTemplate"></div>' +
"</div>" +
"</div>" +
"</div>",
restrict: "E",
transclude: false,
replace: true,
scope: true,
link: function postLink(scope, element, attrs) {
scope.$watch(attrs.visible,
function(value) {
if (value === true)
$(element).modal("show");
else
$(element).modal("hide");
});
$(element).on("shown.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = true;
});
});
$(element).on("hidden.bs.modal",
function() {
scope.$apply(function() {
scope.$parent[attrs.visible] = false;
$rootScope.showMiscModal=false;
});
});
}
};
});
Функции:
$scope.showInternalNotes = function() {
$rootScope.showMiscModal = true;
$scope.selectedTemplate = "/desktopmodules/mvc/TechSheetMaint/AngularTemplates/InternalNotes.html?"+Math.floor((Math.random() * 10000000) + 1);
$scope.getStatusChanges()
};
$scope.showCustomerContact = function() {
$rootScope.showMiscModal = true;
$scope.selectedTemplate= "/desktopmodules/mvc/TechSheetMaint/AngularTemplates/CustomerContact.html?"+Math.floor((Math.random() * 10000000) + 1);
$scope.getStatusChanges()
};
$scope.showStatusChanges = function() {
$rootScope.showMiscModal = true;
$scope.selectedTemplate = "/desktopmodules/mvc/TechSheetMaint/AngularTemplates/StatusChanges.html?"+Math.floor((Math.random() * 10000000) + 1);
$scope.getStatusChanges();
};
Аякс:
$scope.getStatusChanges = function() {
const deferred = $q.defer();
const successFunction = function(response) {
if (!checkLogin(response, "getStatusChanges")) return;
$scope.statusChanges = response.data;
//alert(JSON.stringify(response.data));
deferred.resolve();
};
const failureFunction = function(data) {
console.info(`Error${angular.toJson(data)}`);
deferred.reject();
};
TechSheetFactory.getStatusChanges(successFunction, failureFunction,$scope.TechSheetInfo.WorkOrder.WorkOrderID);
return deferred.promise;
};
Используйте директиву
ng-include.