我知道很多關於如何創建角度動態指令映射的相關帖子,但在我的情況下我找不到任何類似的東西。正如描述所示,我正在試圖根據對象屬性的值來制定一個動態指令,該html被更改。我把我的問題簡化爲這種情況:角度js動態指令傳遞模型屬性
我有一個對象「小工具」,它有一個屬性名稱「類型」的列表。我要取決於這個列表的類型屬性來根據屬性來呈現html。更具體地說,Widget.type可以有3個值,例如:widget1,widget2。所以在我的情況下,我希望指令返回文件小部件* .html。 (widget1.html的widget類型「widget1」等)。儘管我使用屬性將參數傳遞給了指令,但該值不會被計算,並且字符串widget.type會返回。
你能幫我嗎? Thx提前。
app.js文件:
var app = angular.module("MainCtrl", []);
app.controller("myCtrl", function($scope) {
function Widget(type){
this.type=type;
}
$scope.widgets=[];
$scope.widgets.push(new Widget('widget1'),new Widget('widget2'),new Widget('widget3'));
});
app.directive('widget', function() {
return {
restrict: 'E',
scope: {
obj: '='
},
templateUrl: function(element,attr){
//console.log(attr);
console.log(attr.obj);
return attr.obj+'.html';
}
}
});
index.html文件:
<!DOCTYPE html>
<html ng-app="MainCtrl">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<!-- css -->
<link rel="stylesheet" href="style.css" />
<!-- utilities -->
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<!-- angular module file -->
<script src="script.js"></script>
</head>
<body ng-controller="myCtrl">
<div ng-repeat="widget in widgets">
{{widget.type}}
<widget obj='widget.type' ></widget>
</div>
</body>
widget1.html文件:
<div class="widget">
widget1:{{widget.type}}
</div>
widget2.html,widget3.html是相同的
注意控制檯ou輸入指令。
我創建了一個plunker所以它更容易注意到這個問題:http://plnkr.co/edit/ulBSQQrqpSV9g3BNGRhO?p=preview
控制檯錯誤:錯誤:[$ compile:tpload]加載模板失敗:widget.type.html(HTTP狀態:404 Not Found)。你沒有這個html文件,是嗎? – matmo
@matmo widget.type.html不應該是這樣的。表達式widget.type應該評估爲相應的類型 – JmRag