Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 在角度指令中更改内部文本_Angularjs_Dom_Coffeescript - Fatal编程技术网

Angularjs 在角度指令中更改内部文本

Angularjs 在角度指令中更改内部文本,angularjs,dom,coffeescript,Angularjs,Dom,Coffeescript,在我看来,这应该是直截了当的,但我认为我误解了这里的操作顺序。文档对我来说有点难理解,我在这里找到的答案让我更接近答案,但还不够 我试图使用一个指令将一个范围变量(包含一个字符串)放置到DOM中,我想操纵该文本,并最终创建一个“读取更多”文本截断函数 link: (scope, element, attrs) -> commentString = scope.commentary ... ## perform string manipulation here elemen

在我看来,这应该是直截了当的,但我认为我误解了这里的操作顺序。文档对我来说有点难理解,我在这里找到的答案让我更接近答案,但还不够

我试图使用一个指令将一个范围变量(包含一个字符串)放置到DOM中,我想操纵该文本,并最终创建一个“读取更多”文本截断函数

link: (scope, element, attrs) ->
  commentString = scope.commentary

  ...  ## perform string manipulation here

  element.text(newCommentString)
HTML代码段:

{{commentation}}

角度/咖啡脚本:

  app.directive('readMore', [ ->
    restrict: 'E'
    scope: false
    link: (scope, element, attrs) ->
      console.log(element[0])
      element[0].innerText = element[0].innerText.substring(0, 125) + "..."
  ])
来自该变量的文本被读取到DOM中,console将元素记录为
,并且
{{commentation}}
字符串打印在控制台的标记之间,但是,我的函数不会对其进行操作

我知道它是正确的元素(和索引),但由于某种原因,innerText和innerHTML不会影响DOM上的内容

如果我将
链接中的返回行更改为:

element[0].innerText = "Foo"
我在控制台中的
标记之间什么也得不到,很自然,DOM现在在那里没有内容


关于
link
如何处理DOM中的此元素,我缺少了什么

我的理解是,您在这里处理的元素不是您在标准jQuery函数中处理的JS元素。这是,我宁愿创建一个指令来设置“Read More”元素的模型,并隐藏单击后需要显示的整个文本,而不是DOM manypulation。但这只能通过angularjs ng模型指令实现,不能通过DOM操作实现。

对于angularjs,您不需要DOM

下面介绍几种绑定内容的方法:

用这个

link: function($scope) {
    $scope.otherText = 'Here more text. For example, this maybe come from http-stream.';
}
相反,这是:

element[0].innerText = element[0].innerText.substring(0, 125) + "..."

祝你好运。:-)

Angular使用jQuery(如果可用)或jQLite为元素提供包装,因此使用
html
text
函数:

link: (scope, element, attrs) ->
  commentString = element.html() ## alternatively use element.text()
但是,请注意,
text
html
函数都将返回未计算的字符串
{{commentation}
,而不是
commentation
变量包含的任何字符串值

要解决这个问题,只需使用传递给指令的
链接
函数的
范围
参数来解决
注释

link: (scope, element, attrs) ->
  commentString = scope.commentary

  ...  ## perform string manipulation here

  element.text(newCommentString)
这会将元素文本设置为传递给它的任何字符串。至于更新文本:如果单击了“阅读更多”之类的内容,请准备一个事件处理程序(仍在
链接:
中,如下所示:

element.on('click', ->
  element.text(commentString) ## the full commentary string from above
)

我想你需要仔细阅读有关transclusion的内容。我试着阅读了上面的文档;如果能找到更好的解释来回答这个问题,我会非常高兴!我不使用transclusion,而是将变量作为属性传递进来。
。如果你在SO或plnkr上设置代码,我很乐意处理它是的,处理值from范围参数无疑是更简单的方法。