angularjs - 在范围或 ng-model 上使用“字符串”名称

2024-03-18

在普通的 JavaScript 中,你可以像这样声明变量;

var obj = {};
obj["item-text"] = {};
obj["item text"] = {};

这里给出的例子:http://jsbin.com/petafu/1/edit 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>

如果你真的想要连字符和空格,我可能会选择控制器作为 https://stackoverflow.com/questions/21287794/angularjs-controller-as-syntax-clarification syntax.

View:

<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>

控制器:

app.controller('MainCtrl', function($scope) {
  this.name = 'World';
  this['name1'] = "world1";
  this['name-2'] = "world 2";
  this['name 3'] = "world 3";
});

使用您的obj多变的。

控制器:

var obj = {};
obj["item-text"] = {};
obj["item text"] = {};
$scope.obj = obj;

View:

<body ng-controller="MainCtrl">
  <input ng-model="obj['item text']" />
  <input ng-model="obj['item-text']" />
</body>

http://plnkr.co/edit/OqTN59Ewsc6ydKnjSGbx?p=preview http://plnkr.co/edit/OqTN59Ewsc6ydKnjSGbx?p=preview

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

angularjs - 在范围或 ng-model 上使用“字符串”名称 的相关文章

随机推荐