我在angularjs中创建了一个自定义指令,该指令具有隔离范围和传递参数。我尝试检查指令的控制器/链接中的参数,因为有时参数是一个数组,我只需要一个项目。但这不起作用(未定义的对象)。
directives.directive('dir.displaytaxoname', function () {
return {
restrict: 'E',
replace: true,
scope: {
dfamily: '@' ,
dgenus: '@',
dsn: '@'
},
controller: function ($scope) {
console.log($scope.dsn); // empty string in the console but ok in the rendered view
/*function tools_isArray(arr) { return ( arr instanceof Array ); }*/
// if the dfamily argument is an array i just want the first item
if(tools_isArray($scope.dfamily)){ $scope.dfamily = $scope.dfamily[0]; }
if(tools_isArray($scope.dgenus)){ $scope.dgenus = $scope.dgenus[0]; }
if(tools_isArray($scope.dsn)){ cl("indsn") ; $scope.dsn = $scope.dsn[0]; }
},
templateUrl: "partials/elements/displaytaxoname.html"
}
});
<span>
{{dfamily}} <i ng-show="dgenus!=''">{{dgenus}} </i><i>{{dsn}}</i><br>
</span>
<dir.displaytaxoname dfamily="{{specimen['T_FAMILY']}}"
dgenus="{{specimen['T_GENUS']}}"
dsn="{{specimen['T_SCIENTIFICNAME']}}">
</dir.displaytaxoname>
我尝试了许多与链接/控制器的组合,但不起作用。我该怎么办?
谢谢
如果要将非字符串值传递给指令,则需要直接绑定到外部作用域表达式,而不是属性值(请参见文档),因为属性值始终是a String
。
另外,如果您不能100%确定在编译指令时数据已经存在于外部作用域中,则需要$watch
使用数据,而不仅仅是使用初始值。
scope: {
dfamily: '=', // bind to expression instead of attribute value
// ...
},
controller: function ($scope) {
// watch property value changes instead of using just the initial value
$scope.$watch('dfamily', function (value) {
if (tools_isArray(value)) {
// be extremely careful not to create an infinite cycle here
// (better save the modified values to different variables)
$scope.dfamily = value[0];
}
});
// ...
}
和
<tag dfamily="specimen['T_FAMILY']" ...></tag>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句