javascript - 将 JSON 对象从 Angular 服务传递给指令

标签 javascript json angularjs angularjs-directive angularjs-service

我正在尝试将 JSON 对象从 Angular 服务传递到指令。实际上,我只是想 $compile 一个指令 on-the-go 并将一个对象传递给该指令。

它应该看起来像这样:

var template = '<gmap-info-window layer="layer" marker="marker"></gmap-info-window>',
    content = $compile(template)(searchScope);

指令看起来像这样:

.directive('gmapInfoWindow', [function() {
    scope: {
        marker: '=',
        layer: '='
    },
    link: function(scope, element, attrs) {
        // access objects in attrs
    }
}]);

那是行不通的。我在 attrs.marker 和 attrs.layer 中得到的只是纯字符串。

现在我尝试并完成的是使用 $compile 函数的 transcludeFn 函数。它有效,但我认为这不是实现我想要完成的目标的正确方法。

 var template = '<gmap-info-window></gmap-info-window>',
     content = $compile(template)(searchScope, null, {
         parentBoundTranscludeFn: function() {
              return {
                  marker: _marker,
                  layer: _layer
              };
          }
      });

指令看起来像这样:

.directive('gmapInfoWindow', [function() {
    scope: {},
    link: function(scope, element, attrs, controller, transcludeFn) {
        var objects = transcludeFn();
        // The marker and layer are in objects now!
    }
}]);

我无法想象没有其他方法可以做我想做的事。这看起来有点脏。感谢您的见解!

最佳答案

All I get in the attrs.marker and attrs.layer is plain strings.

根据定义,您需要了解属性始终是一个字符串。你不可能在那里有一个对象。 Angular 所做的是根据指令的范围配置在适当的上下文(编译范围)中评估这些属性(字符串)的值。然后,此评估的结果在链接函数的 scope 对象中可用。这是您需要使用的:

link: function(scope, element, attrs) {
    console.log(scope.marker, scope.layer);
}

关于javascript - 将 JSON 对象从 Angular 服务传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32440379/

相关文章:

javascript - 是否可以在 JavaScript 中的对象声明内执行循环

ruby-on-rails - 如何断言它使用正确的 json 呈现?

javascript - 想要在选择多个中添加无作为值

javascript - 单击事件不会在 for 循环的每次迭代中触发

javascript - 如何通过单击 jquery 中的按钮清除同位素搜索过滤器?

javascript - 使用javascript在页面加载时加载css隐藏图像作为背景图像

php - 合并 Json 格式数组中的重复值

javascript - 检查父状态 Promise 是否已返回值

regex - 如何在 Angular JS 范围内给出正则表达式模式

Javascript - 幻灯片放映上的下一个/上一个按钮 - 新 child 需要帮助