我想要做一个AngularJS指令,该指令从作为指令属性提到的关键字应该返回一个包含范围数据包含的关联数组的字符串的html模板。AngularJS指令查找关联数组
我认为代码片段会更清楚:
我在范围关联数组:
{"mapData":
{"menu1":"Apples",
"menu2":"Strawberries"}}
如何该指令将被调用:
<div ng-controller="menuAngularController">
<menu-dir menuData="menu1"></menu-dir>
</div>
HTML,应该是在角度解释后返回:
<li dropdown class='dropdown dropdown-fw'>
<a href='#' class='dropdown-toggle' dropdown-toggle>Apples
<span class='caret'></span>
</a>
<ul class='dropdown-menu' role='menu' ng-transclude></ul>
</li>
是我工作的指令,没有令人信服的结果:
angular.module('Module.Directives',[]).directive('menuDir', function(){
restrict:'E',
̶t̶r̶a̶n̶c̶l̶u̶d̶e̶ transclude:true,
replace:true,
scope:{
menuData:'@'
},
template :"<li dropdown class='dropdown dropdown-fw'><a href='#' class='dropdown-toggle' dropdown-toggle>"+
"{{test}} <span class='caret'></span></a>"+
"<ul class='dropdown-menu' role='menu' ng-transclude></ul></li>",
link:function(scope, elem, attrs, controllers ̶,̶ ̶$̶s̶c̶o̶p̶e̶) {
//I put $watch because my AngularJS controller load data from an external service, so I listen change on data loaded
scope.$watch('menuData', function(newValue, oldValue){
//I get the data of the array by the id
scope.test = "{{mapData['"+newValue+"']}}";
});
});
角控制器:
angular.module('MenuAngular.Controller', [])
.controller('menuAngularController', MenuAngularController);
MenuAngularController.$inject = ['menuAngularServices', '$scope'];
function MenuAngularController(menuAngularServices, $scope){
//the service (tested, all is ok on this side) that return the data on a map
menuAngularServices.initMenu.query({},function(data){
$scope.mapData= data.mapMessages;
},
function(error){
console.log(error);
});
其实,我成功获得“{{属于MapData [菜单1]}} “印在屏幕上,但没有被Angular的价值取代。
有没有人有想法? (我的英语水平很抱歉,谢谢你提前!)
假设你有属于MapData某处该指令(我没有看到它),你可以尝试scope.test = mapData [newValue]; – rrd
我编辑我的帖子以添加控制器的代码。该值在$ scope(父范围)上,而不在范围内。 –