【问题标题】:angularjs directive : $watch returns a string rather the objectangularjs 指令:$watch 返回一个字符串而不是对象
【发布时间】:2013-11-11 18:11:39
【问题描述】:

我无法让 $watch 向我返回一个 Javascript 对象。它总是我一个字符串,而不是像: "{'text':'你好'}"

这是我的指令(CoffeeScript):

app.directive 'progressIndicator', ->
restrict : 'E'
scope : { progress : '@' }
link : (scope,element,attrs) ->
        scope.$watch 'progress' , (v) ->
            scope.curPrg = v
template :  '<label>In progress: {{curPrg.text}}' +
               '<progress></progress>'

还有 HTML 代码:

<progress-indicator progress={'text':'Hello'}></progress-indicator>

我试过 attrs.$observe :同样的行为。

我尝试过控制器而不是链接:相同的行为。

怎么了?最好的方法是什么。 最后,我希望能够做到:

【问题讨论】:

  • 编译后的(到 javascript 的)指令是什么样的?
  • 来自 the documentation: @@attr - 将本地范围属性绑定到 DOM 属性的值。结果始终是字符串,因为 DOM 属性是字符串。 阅读其余文档。

标签: angularjs directive watch


【解决方案1】:

问题在于您要链接的范围。 @ 符号将数据链接为字符串而不是对象。

试试=,像这样:

app.directive 'progressIndicator', ->
restrict : 'E'
scope : { progress : '=' }
link : (scope,element,attrs) ->
    scope.$watch 'progress' , (v) ->
        scope.curPrg = v
template :  '<label>In progress: {{curPrg.text}}' +
           '<progress></progress>'

【讨论】:

  • 如果我放入 HTML 文件 而不是 ,则 = 有效。为什么?
  • 你做了一个角度指令,类似于 ng-repeat 或 ng-click。 Angular 知道接受在 progress="" 中输入的字符串并使用传入的名称检查数据/函数的当前范围
猜你喜欢
  • 2017-09-22
  • 1970-01-01
  • 2017-07-18
  • 2011-07-29
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多