希望你一切都好!
嗯,基本上我的问题与绑定(bind)嵌套变量有关。正如您在我的 jsfiddle 中看到的那样,我有一个表,我需要在它的每一列中都有动态链接。所以我创建了一个指令来创建 <a>
href 元素动态地,这取决于将填充表和表列定义中的数据。
这是 HTML 代码:
<table ng-controller="MyCtrl" border=1 width="100%">
<tr ng-repeat="item in dataGrid">
<td ng-repeat="itemColumn in columnDefs" width="30%" style="text-align: center">
<link-cell-template columnitem="itemColumn" parentitem="item" />
</td>
</tr>
</table>
这是指令代码:
myApp.directive('linkCellTemplate', function ($compile, $templateCache) {
return {
restrict: 'E',
require: '?ngModel',
replace: true,
transclude: false,
scope: {
columnitem: '=',
parentitem: '='
},
link: function (scope, element, attrs, ngModelCtrl) {
scope.hrefValue = angular.isDefined(scope.columnitem.linkUrl) ? scope.columnitem.linkUrl : "";
scope.linkValue = angular.isDefined(scope.columnitem.linkDescription) ? scope.columnitem.linkDescription : scope.parentitem[scope.columnitem.field];
// Append the HTML Layout in the Element
element.append($compile($templateCache.get('linkCellTemplate.html'))(scope));
}
};
}).run(["$templateCache", function ($templateCache) {
$templateCache.put("linkCellTemplate.html",
"<a href=\"{{hrefValue}}\" role=\"button\" style=\"cursor: pointer;\">{{linkValue}}</a>");
}]);
我的指令基于模板,在模板中我有两个变量 {{hrefValue}}
和{{linkValue}}
我在指令的链接函数内处理哪些值。给我带来麻烦的是 {{linkValue}}
,根据列定义,如果没有定义linkDescription属性,则以列字段属性为值,否则为linkDescription。
该指令适用于几乎所有数据。正如您在 $scope.dataGrid
中看到的那样变量,我有一个关联数组的数组。如果你检查jsfiddle,你会发现第三列被定义为像第二列一样显示列字段内容(而不是linkDescription),但在这种情况下,运行时不会显示链接。经过检查代码,发现问题与字段本身有关。在第二列中,字段为 Description
,但第三列是 Location.Name
(就像在 dataGrid 中一样)。 “嵌套变量”(Location.Name)是导致问题的变量。
我一直在尝试找到一种方法,让我的指令适用于所有类型的字段(简单如Description
或嵌套如Location.Name
)。你知道我错过了什么吗?任何想法都会有帮助。
谢谢!
最佳答案
在这种情况下(即括号中存在复杂表达式),您将必须使用 $parse
。幸运的是,这很简单:
myApp.directive('linkCellTemplate', function ($compile, $templateCache, $parse) {
...
scope.linkValue = angular.isDefined(scope.columnitem.linkDescription) ?
scope.columnitem.linkDescription
// here is the change
: $parse(scope.columnitem.field)(scope.parentitem);
关于javascript - Angular JS 中的绑定(bind)问题(嵌套变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19724491/