从控制器传递数据数组到自定义指令?
从控制器传递数据数组到自定义指令?
我试图从一个Angular控制器传递一个对象数组到一个自定义指令元素,并通过ng-repeat来迭代对象,但是我没有得到数据。\n
$scope.mydata=[ { "_id":"1", displayConfig:[ { "fieldIndex": 2, "propertyName": "o1", "propertyValue": "sree" },{ "fieldIndex": 2, "propertyName": "o2", "propertyValue": "sravs" },{ "fieldIndex": 2, "propertyName": "o3", "propertyValue": "sree" }, ], "name": "Alabama", "abbreviation": "AL" }, ... ];
\nhtml文件...........\n
\ndirective.js\n
.directive('search', function($timeout) { return { restrict: 'AEC', scope: { items: '=', prompt:'@', title: '@', subtitle:'@', model: '=', onSelectupdate:'&' }, link:function(scope,elem,attrs){ scope.handleSelection=function(selectedItem){ scope.model=selectedItem; console.warn(scope.items); scope.current=0; scope.selected=true; $timeout(function(){ scope.onSelectupdate(); },200); }; scope.current=0; scope.selected=true; scope.isCurrent=function(index){ return scope.current==index; }; scope.setCurrent=function(index){ scope.current=index; }; }, templateUrl : TAPPLENT_CONFIG.HTML_ENDPOINT[0]+'home/genericsearch.html' } })
\ngenericsearch.html\n
{{item[title]}}x
\n请帮助解决这个问题。\n提前感谢。
问题的出现原因是:在自定义指令中,尝试在获取参数之前使用参数。
解决方法是:确保正确观察参数。可能是因为在获取参数之前尝试使用它。
这是一个自定义指令的代码示例,其中包含了一个参数items:
.directive('search', function($timeout) {
return {
restrict: 'AEC',
scope: {
items: '=',
prompt:'@',
title: '@',
subtitle:'@',
model: '=',
onSelectupdate:'&'
},
link:function(scope,elem,attrs){
scope.handleSelection=function(selectedItem){
scope.model=selectedItem;
console.warn(scope.items);
scope.current=0;
scope.selected=true;
$timeout(function(){
scope.onSelectupdate();
},200);
};
scope.$watch("items", function(newData) {
console.log("Items: ", newData);
});
scope.current=0;
scope.selected=true;
scope.isCurrent=function(index){
return scope.current==index;
};
scope.setCurrent=function(index){
scope.current=index;
};
},
templateUrl : TAPPLENT_CONFIG.HTML_ENDPOINT[0]+'home/genericsearch.html' }
})
问题提出者要求实现一个可以选择多个项的搜索框。他希望能够在自定义指令中实现这一功能,并且不使用已有的指令。
回答者建议使用现有的Angular指令来实现这一功能,并提供了一个示例链接,以展示如何使用现有的指令来实现多项选择的搜索框。
问题提出者解释说他正在创建一个自定义指令,因此不想使用现有的指令。回答者表示虽然他理解问题提出者的要求,但使用现有的指令会更容易。
问题提出者继续询问如何使用自定义指令创建带有多个选择标签的搜索框。回答者建议他先了解现有指令的工作原理,并尝试创建正确的HTML结构。
这个问题的出现原因是尝试在获取参数之前使用参数,解决方法是确保正确观察参数。问题提出者希望能够在自定义指令中实现一个带有多个选择标签的搜索框,并且不使用现有的指令。回答者建议他使用现有的指令,并提供了示例链接来帮助他理解如何实现多项选择的搜索框。
问题原因:在这个问题中,作者想要将数据从控制器传递到自定义指令中,但是他的做法让人感到有些不对劲。
解决方法:作者提出了两种解决方法。第一种方法是在link函数中通过attrs参数来访问数据。具体做法是在link函数中使用attrs.model来获取数据。然而,这种方法可能并不是最明智和最容易使用的方法。第二种方法是使用一个service或者factory来实现数据的传递。作者提供了一个链接Example of service/factory utilisation来展示如何使用service或者factory来传递数据。
结合这两种方法,可以在link函数中使用attrs参数来访问数据,并且将数据存储在service或者factory中,以便在整个应用程序中共享和使用。