Angular JS(嵌套变量)中的绑定问题

Binding issue in Angular JS (Nested Variables)

本文关键字:绑定 问题 变量 JS 嵌套 Angular      更新时间:2023-09-26

希望你没事!

好吧,基本上我的问题与绑定嵌套变量有关。正如您在我的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}},根据列定义,如果没有定义链接描述属性,它将以列字段属性作为值,否则将是链接描述。

该指令几乎适用于所有数据。正如您在$scope.dataGrid变量中看到的那样,我有一个关联数组数组。如果您检查 jsfiddle,您会发现第 3 列被定义为像第 2 列一样显示列字段内容(而不是 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 不允许这样的结构(这很好 imo):

object['one'].two.three != object['one.two'].three

因为'one''one.two'是存储在哈希表中的不同键。

幸运的是,angularjs 为此类操作提供了$parse http://jsfiddle.net/s7gn8/4/。