在普通的 JavaScript 中,你可以像这样声明变量;
var obj = {};
obj["item-text"] = {};
obj["item text"] = {};
此处给出示例:http://jsbin.com/petafu/1/edit
而且完全没问题。但这似乎不适用于 $scope
。我试图这样做但无法真正理解为什么,但找不到任何资源谈论它......
JS
app.controller('ControllerName', function($scope){
$scope['item text'] = {};
$scope['item-text'] = {};
});
HTML
<div ng-model="item text"></div>
<div ng-model="item-text"></div>
最佳答案
如果你真的想要连字符和空格,我可能会选择 controller as语法。
查看:
<body ng-controller="MainCtrl as ctrl">
<p>Hello {{ctrl.name}}!</p>
<input ng-model="ctrl.name1" />
<input ng-model="ctrl['name-2']" />
<input ng-model="ctrl['name 3']" />
</body>
Controller :
app.controller('MainCtrl', function($scope) {
this.name = 'World';
this['name1'] = "world1";
this['name-2'] = "world 2";
this['name 3'] = "world 3";
});
使用您的 obj
变量。
Controller :
var obj = {};
obj["item-text"] = {};
obj["item text"] = {};
$scope.obj = obj;
查看:
<body ng-controller="MainCtrl">
<input ng-model="obj['item text']" />
<input ng-model="obj['item-text']" />
</body>
关于javascript - angularjs - 在范围或 ng-model 上使用 'string' 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25043148/