javascript - AngularJS 返回大括号中的变量名称,而不是值

标签 javascript angularjs

这可能非常简单,但我找不到适当的文档来解释如何克服我的问题,这里是:我有一个像这样的中继器...

  <tr ng-repeat="thing in things">
        <td>{{ thing.name }}</td>
        <td>{{ thing.category }}</td>
        <td>{{ thing.content }}</td>
        <td>{{ thing.confirms }}</td>
        <td>{{ thing.declines }}</td>
        <td> <button ng-click="doSomething('{{ thing }}')">Do what we want</button></td>
    </tr>

现在一切正常,符合预期。在我编写的服务中的 doSomething 函数中,我希望传递一个“thing”对象作为参数,我已将其转换为字符串以避免错误(稍后我将转换它)。现在,当我将该对象输出到我的服务时,不会返回对象内容(尽管它们显示在渲染的 HTML 中)。传递给我的服务的是字符串“{{ thing }}”而不是对象值(因此我的 JSON.parse 失败),这是从 Chrome 开发工具呈现的 HTML:

doSomething('{"name":"Debbie Harry","id":"526f9eb7e4b0b5062e14c1dc","category":"Basic Info","content":"Debbie Harry is cool","confirms":5,"declines":0}')

我该如何克服这个问题?如何确保传递的是 JSON 对象而不是 AngularJS 大括号声明?

如果我没有很好地解释自己,请说明,我将重新表述我的问题。

最佳答案

这样做

<td> <button ng-click="doSomething(thing)">Do what we want</button></td>

或者你可以这样做(但不要这样做)

<td> <button ng-click="doSomething(" + {{thing}} + ")">Do what we want</button></td>

ngClick 指令读取值并将其解析为 JavaScript,因此您可以按原样使用 thing 变量。 thing 变量可在 ng-repeat block 内访问。

如果你深入研究 angularjs 源代码,你可以找到这段代码。这将帮助您了解 ngClick 指令的工作原理。

var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress'.split(' '),
function(name) {
  var directiveName = directiveNormalize('ng-' + name);
  ngEventDirectives[directiveName] = ['$parse', function($parse) {
    return function(scope, element, attr) {
      var fn = $parse(attr[directiveName]);
      element.bind(lowercase(name), function(event) {
        scope.$apply(function() {
          fn(scope, {$event:event});
        });
      });
    };
  }];
}
);

关于javascript - AngularJS 返回大括号中的变量名称,而不是值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19976730/

相关文章:

JavaScript 执行直到按键

javascript - jshint 和 Function() 得到 : Missing 'new' prefix when invoking a constructor

jquery - 如何使用 angularjs 删除对象中的 [

javascript - Angular 1.5 : Access bindToController properties inside controller

javascript - Angular 数组循环和排序函数

javascript - 在 Angular js中将下拉列表中的第一个值设为粗体

javascript - 当使用 element.style = <some CSSStyleDeclaration> 使元素消失

javascript - 自动增加文本区域大小

javascript - 循环遍历坐标数组以在 html Canvas 上绘制线条

javascript - 对对象使用 ng-repeat