假设我有一个简单的指令,如下所示:

app.directive('seo', function() {
    return {
        template: '<meta ng-repeat="tag in data" {{tag.attribute}}="{{tag.name}}" content="{{tag.content}}" />',
        scope : {
            data: '='
        },
        restrict: 'A',
        replace:true
    }
});


因此,所有这些操作就是通过传递一些数据来自动创建元标记:

的HTML

<meta seo data="data" />


数据

[{
    attribute : 'name',
    content : 'foo',
    name : 'image'
},
{
    attribute : 'property',
    content : 'bar',
    name : 'title'
}];


因此,目的是创建一个模板,该模板会显示以下内容:

<meta class="ng-scope" ng-repeat="tag in data" name="image" content="foo" seo data="data">
<meta class="ng-scope" ng-repeat="tag in data" property="title" content="bar" seo data="data">


我如何使用Angularjs动态更改属性,显然我在等号不起作用之前使用{{tag.attribute}}作为特定属性所采用的方法。

最佳答案

尝试两个方向的方法。

第一个(seo)将使用ng-repeat进行迭代,并在每次迭代中将当前的tag对象传递给第二个(seo-tag)。第二个将根据对象属性修改元素属性。

例:

app.directive('seo', function() {
  return {
    template: '<meta ng-repeat="tag in data" seo-tag tag="tag" />',
    scope : {
      data: '='
    },
    restrict: 'A',
    replace: true
  }
});

app.directive('seoTag', function() {
  return {
    scope : {
      tag: '='
    },
    restrict: 'A',
    replace: true,
    link: function (scope, elem, attrs) {
        attrs.$set(attrs.$normalize(scope.tag.attribute), scope.tag.content);
    }
  }
});


这段代码并不完美,但是我认为这是一个很好的基础。

doc可能会有所帮助。

编辑:

我什至会跳过seo指令,而仅将ng-repeatseo-tag一起使用。它有两个层次,太复杂了,仍然很简单,代码应该很不错:

<meta ng-repeat="tag in data" seo-tag tag="tag" />


在模板中。

10-05 20:42
查看更多