动态匹配传递给指令的变量
Match variable passed to directive dynamically
我为 HTML 图像创建了一个指令,它允许我为我经常使用的图像存储 URLs 和 alt 标签,所以我只需要给它一个特定的值通过其数据字段(代码中的数据类型),它被具有相应 URL 和 alt 标记的图像替换。我这样做是为了不必一直写出标签,并且可以在代码中的一个地方更改它。
到目前为止,只要我将值作为字符串传递,它就可以很好地工作。但是为了使指令真正有用,我需要它还可以将值作为变量传递(例如在 ng-repeat 中)。
这是我的设置:
指令 - 基于传递的名为 type 的变量构建 img:
app.directive('tsTypeImage', function() {
return {
restrict: 'E',
replace: true,
scope: {
type: '='
},
template:'<img src="{{ type.imgURL }}" alt="{{ type.name }}">'
};
});
控制器:
app.controller("ctrl", function($scope) {
$scope.fire = { name: "Fire", imgURL: "/images/fire.png" };
$scope.water = { name: "Water", imgURL: "/images/water.png" };
$scope.lightning = { name: "Lightning", imgURL: "/images/lightning.png" };
});
HTML:
<body ng-app="tcgApp" ng-controller="ctrl" ng-init="type='fire'">
<!-- this works -->
<ts-type-image data-type="fire"></ts-type-image>
<!-- this does not work -->
<ts-type-image data-type="{{ type }}"></ts-type-image>
</body>
我已经用插值或解析尝试了很多东西但没有成功。这是我的第一个 AngularJS 项目,所以也许我什至 运行 走错了方向,有一种更简单的方法可以实现这一点。如果是这样,请告诉我:)
不要将插值与 AngularJS 表达式混合使用:
<body ng-app="tcgApp" ng-controller="ctrl" ng-init="type='fire'">
<!-- this works -->
<ts-type-image data-type="fire"></ts-type-image>
<!-- this does not work -->
̵<̵t̵s̵-̵t̵y̵p̵e̵-̵i̵m̵a̵g̵e̵ ̵d̵a̵t̵a̵-̵t̵y̵p̵e̵=̵"̵{̵{̵ ̵t̵y̵p̵e̵ ̵}̵}̵"̵>̵<̵/̵t̵s̵-̵t̵y̵p̵e̵-̵i̵m̵a̵g̵e̵>̵
<ts-type-image data-type="this[type]"></ts-type-image>
</body>
在 AngularJS 表达式中使用 this
标识符来访问 $scope
对象。
有关详细信息,请参阅
我为 HTML 图像创建了一个指令,它允许我为我经常使用的图像存储 URLs 和 alt 标签,所以我只需要给它一个特定的值通过其数据字段(代码中的数据类型),它被具有相应 URL 和 alt 标记的图像替换。我这样做是为了不必一直写出标签,并且可以在代码中的一个地方更改它。
到目前为止,只要我将值作为字符串传递,它就可以很好地工作。但是为了使指令真正有用,我需要它还可以将值作为变量传递(例如在 ng-repeat 中)。
这是我的设置:
指令 - 基于传递的名为 type 的变量构建 img:
app.directive('tsTypeImage', function() {
return {
restrict: 'E',
replace: true,
scope: {
type: '='
},
template:'<img src="{{ type.imgURL }}" alt="{{ type.name }}">'
};
});
控制器:
app.controller("ctrl", function($scope) {
$scope.fire = { name: "Fire", imgURL: "/images/fire.png" };
$scope.water = { name: "Water", imgURL: "/images/water.png" };
$scope.lightning = { name: "Lightning", imgURL: "/images/lightning.png" };
});
HTML:
<body ng-app="tcgApp" ng-controller="ctrl" ng-init="type='fire'">
<!-- this works -->
<ts-type-image data-type="fire"></ts-type-image>
<!-- this does not work -->
<ts-type-image data-type="{{ type }}"></ts-type-image>
</body>
我已经用插值或解析尝试了很多东西但没有成功。这是我的第一个 AngularJS 项目,所以也许我什至 运行 走错了方向,有一种更简单的方法可以实现这一点。如果是这样,请告诉我:)
不要将插值与 AngularJS 表达式混合使用:
<body ng-app="tcgApp" ng-controller="ctrl" ng-init="type='fire'">
<!-- this works -->
<ts-type-image data-type="fire"></ts-type-image>
<!-- this does not work -->
̵<̵t̵s̵-̵t̵y̵p̵e̵-̵i̵m̵a̵g̵e̵ ̵d̵a̵t̵a̵-̵t̵y̵p̵e̵=̵"̵{̵{̵ ̵t̵y̵p̵e̵ ̵}̵}̵"̵>̵<̵/̵t̵s̵-̵t̵y̵p̵e̵-̵i̵m̵a̵g̵e̵>̵
<ts-type-image data-type="this[type]"></ts-type-image>
</body>
在 AngularJS 表达式中使用 this
标识符来访问 $scope
对象。
有关详细信息,请参阅