如何将对象传递到角度.js指令中?内插参数似乎是序列化的



我正在尝试将JavaScript对象传递到角度指令中。我像这样调用它:

<thing-badge thing="{{thing}}"></thing>

该指令如下所示:

directives.directive('thingBadge', function() {
    return {
        restrict: 'E',
        controller: function($scope) {
        },
        link: function(scope, element, attrs, $scope) {
          attrs.$observe('thing', function(thing) {
              console.log(thing);
          }
        }
     }
}

假设这个东西是一个JS对象:{'an': "object'}。我想在我的指令中获取这个对象的值。相反,我得到了对象的序列化:字符串类型的'{"an": "object"}'

如果我通过number(例如 <thing-badge thing="{{thing.id}}"></thing> ( 我也得到一个字符串,例如 "0" .

如何将实际对象传递到其中?

您需要添加一个隔离范围:

directives.directive('thingBadge', function() {
    return {
        restrict: 'E',
        scope: {
            thing: '='
        },
        controller: function($scope) {
        },
        link: function(scope, element, attrs, $scope) {
          attrs.$observe('thing', function(thing) {
              console.log(thing);
          }
        }
     }
}

而且您不应该在元素中使用大括号表示法:

<thing-badge thing="thing"></thing-badge>

最新更新