我想要帮助在 templateUrl 中获得价值。我已经经历过类似的问题,例如Set templateUrl base on attribute in directive
我的目标
我想在从HTML调用指令时设置一个属性。此属性将具有来自 json 对象的动态值。我想在指令的 templateUrl 函数中使用这个属性。
你可以在这里看到更多了解我的问题 - jsfiddle
我想根据属性值呈现复选框或单选模板。
请帮忙。
我知道ng-include方法,所以请建议替代解决方案。
我想要帮助在 templateUrl 中获得价值。我已经经历过类似的问题,例如Set templateUrl base on attribute in directive
我的目标
我想在从HTML调用指令时设置一个属性。此属性将具有来自 json 对象的动态值。我想在指令的 templateUrl 函数中使用这个属性。
你可以在这里看到更多了解我的问题 - jsfiddle
我想根据属性值呈现复选框或单选模板。
请帮忙。
我知道ng-include方法,所以请建议替代解决方案。
scope在 tempalteUrl 函数中无法访问。在link函数中,您可以访问模板 Url 以及范围。我在这里更改了您的代码。
angular.module("myApp",[]).controller("myCtrl",['$scope',function($scope) {
$scope.dynamicAttr = [
{
style:"stdRadio",
label:"First Box"
},
{
style:"stdCheck",
label:"Second Box"
}
];
}]).directive("dynamicComponent",['$compile','$http','$templateCache',function($compile, $http,$templateCache) {
return {
scope:{
sourceData:"=sourceData"
},
restrict:"E",
link: function (scope, element, attrs) {
$http.get((scope.sourceData.style == "stdRadio")?"dynamicComponentRadio.html":"dynamicComponentCheckBox.html", {cache: $templateCache}).then(function(data){
element.html(data.data);
return $compile(element.contents())(scope);
});
}
}
}]);