通过angular指令设置元素的属性text / value?

时间:2014-08-01 03:51:30

标签: javascript angularjs angularjs-directive angular-ui-router

如何设置attr文本?

尝试通过它的内容attr。

设置元标记描述的值
<title  update-title></title>
<meta name="description" update-description content="">

我创建了一个简单的2指令:

第一个有效:这设置了标题标签

app.directive('updateTitle', function($rootScope) {
  return {
    link: function(scope, element) {

      var listener = function(event, toState, toParams, fromState, fromParams) {
        var title = 'Default Title';
        if (toState.data && toState.data.pageTitle) {
            title = toState.data.pageTitle;
        }
        element.text(title)
      };

      $rootScope.$on('$stateChangeStart', listener);
    }
  }
})

这个不起作用:因TypeError而获得.text()

app.directive('updateDescription', function($rootScope) {
  return {
    link: function(scope, element, attr) {

      var listener = function(event, toState, toParams, fromState, fromParams) {
        var desc = 'Default Description';
        console.log(toState.data);
        if (toState.data && toState.data.description) {
            desc = toState.data.description;

        }
        //getting a type error because i cant set the .text() of an attr.
        attr.content.text(desc);

      };

      $rootScope.$on('$stateChangeStart', listener);
    }
  }
})

路线:

.state('root.app.work', {
  url: 'work',
  data: {
    pageTitle: 'work',
    description: 'work desc'
  }
})

1 个答案:

答案 0 :(得分:2)

变化:

attr.content.text(desc);

attr.$set('content', desc);

您可以看到其文档 here