我正在制作一个非常简单的自定义指令,它将在范围内显示为 2D 数组中的一列产品详细信息。自定义指令将有一个属性,该属性将传递,必须显示数组的哪列。请看下面的 plnkr--
https://plnkr.co/edit/zVIRZ8ADdQB4X8dSFOaJ
从UI我正在使用这个-
<show-products type="name"></show-products>
当前显示数组的所有数据。 但是我只需要显示 1 列数据,该列将由指令属性提及(例如 plnkr 中的 -name)
在链接函数中,我能够使用以下代码获取列名-
link: function postlink(scope, element, attr) {
console.log("...type..." + attr["type"]); // prints name
}
但是如何将该字段名称传递给模板?
template: '<div ng-repeat="x in products">{{x}}</div>' // i need to print only name column here
您还可以获得模板函数的这些属性,只需创建一个函数而不是字符串,然后将属性类型传递到产品类型变量中即可。
模板的函数版本的文档可以在 angular v1 文档中找到:https://docs.angularjs.org/guide/directive
有关更多信息,请参阅下面的代码片段。
<html ng-app="app">
<head>
<title>Directives</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.js"></script>
<script>
angular.module("app", []);
angular.module("app")
.controller("ctrl", ctrl)
.directive("showProducts", showProducts);
function ctrl($scope) {
$scope.products = [{
name: "Apples",
category: "Fruit",
price: 1.20,
expiry: 10
}, {
name: "Bananas",
category: "Fruit",
price: 2.42,
expiry: 7
}, {
name: "Pears",
category: "Fruit",
price: 2.02,
expiry: 6
}];
};
function showProducts() {
return {
template: (child, attributes) => {
return `<div ng-repeat="x in products">{{x["${attributes["type"]}"]}}</div>`
}
};
};
</script>
</head>
<body>
<div class="panel panel-default">
<div class="panel-body" ng-controller="ctrl">
<show-products type="name"></show-products>
</div>
</div>
</body>
</html>