在 HTML 模板中使用短划线绑定范围属性

binding scope property with a dash in html template

本文关键字:绑定 范围 属性 HTML      更新时间:2023-09-26

出于某种原因,我必须在像test-name这样的属性中使用破折号,并且不能使用testNametestname

angular.module('testApp')
.controller('TestController',function($scope){
  //neither 'testname' nor 'testName', only 'test-name'
  $scope['test-name'] = 'Test name...';
});

现在我想在 html 模板中绑定它:

<div ng-controller="TestController">
  This is {{test-name}}
</div>

我也尝试过{{testname}}{{testName}}但不起作用。保持$scope['test-name']

有什么办法吗?


目前,这会产生如下结果:

This is 0

但预期的结果是这样的:

This is Test name...

试试这个,它应该可以工作:

<div ng-controller="TestController">
  This is {{this['test-name']}}
</div>
这是因为

{{test-name}}$parseProvider解析并以角度Lexer时,-被重新识别为减号运算符。

https://github.com/angular/angular.js/blob/master/src/ng/parse.js#L1005

{{this['test-name']}}应该有效