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



我对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样式,但我很难相信这是正确的方法。

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

假设您能够解析字符串并根据需要提取数据,将其添加到作用域,然后在模板中使用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>

最新更新