【问题标题】:Set an element's attribute text/value through an angular directive?通过角度指令设置元素的属性文本/值?
【发布时间】:2014-08-01 03:51:29
【问题描述】:

如何设置属性的文本?

试图通过它的内容属性设置元标记描述的值。

<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);
    }
  }
})

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

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'
  }
})

【问题讨论】:

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


    【解决方案1】:

    变化:

    attr.content.text(desc);
    

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

    你可以查看它的文档here

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多