繁体   English   中英

在JSON内部创建链接并将其通过AngularJS注入dom

[英]Creating links inside of JSON and injecting it into the dom through AngularJS

我对Angular有点陌生,我试图根据正则表达式的输出来修改一些要绑定的数据。 问题是我正在尝试在此文本中使用“ ng-click”创建元素,以调用函数search()并将正则表达式值传递给该元素。 例如,我想要获取从ajax调用接收到的数据,如下所示:

"{\
    name: 'foo@1.0',\
    children: [\"bar@1.0\", \"baz@1.0\"],\
    ...\
}"

并以这种格式将其绑定到html

<pre>
{
    name: '<a ng-click="search('foo@1.0')>"foo@1.0'</a>,
    children: [
        "<a ng-click="search('bar@1.0')>bar@1.0</a>", 
        "<a ng-click="search('baz@1.0')>baz@1.0</a>",
    ]
    ...
}
</pre>

最后一个陷阱。 由于存在JSON,因此我收到了一些其他功能, 因此无法将其解析为有效JSON

我目前解决此问题的方法是采用正则表达式查找所有类似于name@1.0名称,并用<a ng-click="search($event)"></a>包围它们,然后使用jQuery样式但ID很难相信这是正确的方法。

有谁有解决这个问题的更好方法?

假设您能够解析字符串并根据需要提取数据,则将其添加到作用域,然后在模板中使用ng-repeat

yourDirective.js

yourApp.directive('yourDirective', [function () {
return {
    templateUrl: 'yourDirective.html', 
    link: function(scope, element, attrs) {
    // extract your data from the string and store it on thescope
    scope.name = 'foo@1.0';
    scope.children = [
      'bar@1.0',
      'baz@1.0'
    ]
    scope.search = function(val) {
      console.log('searching for', val);
    }

  };

}]);

yourDirective.html

<pre>
{
    name: '<a ng-click="search(name)">{{name}}</a>',
    children: [
    <a ng-repeat="child in children" ng-click="search(child)">{{child}}</a>
    ]
}
</pre>

用法:

<your-directive></your-directive>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM