这是一个真正问题的简化版本,但我想了解正在发生的情况以及如何解决该问题。我有一个指令,应该加载不同的模板depennding在参数绑定到它。Angular指令动态模板不与绑定一起使用
var app = angular.module('my_app', [])
.controller('controller', Controller)
.directive('dirTwo', DirTwo);
function Controller() {
var este = this;
this.list = ["number", "text", "text"];
this.change = function() {
this.list = this.list.reverse();
}
}
function DirTwo() {
return {
restrict: 'E',
//template: ' Name: {{name}}{{type}}',
template: my_template,
scope: {
type: "="
},
link: function($scope) {
$scope.name = "Pepito";
console.log("scope type: " + $scope.type);
}
}
}
var my_template = function(elem, attrs, $scope) {
console.log("template type: " + attrs.type);
switch (attrs.type) {
case 'number':
return '<a href="#">{{type}}</a>';
break;
default:
return ' ---- '
break;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div class="app" ng-app="my_app" ng-controller="controller as App">
<p>{{App.list}}
<button ng-click="App.change()">Reverse</button>
</p>
<dir-two ng-repeat="item in App.list track by $index" type="item"></dir-two>
</div>
日志中的模板函数打印字item
而不是number
或text
。我如何解决它以正确加载模板?
尝试'type =“{{item}}”'? – GillesC
@GillesC,试过了,错误更大!事实上,你会发现绑定在链接函数中工作,但不在模板中。 – Vandervals