angularjs - 在范围或ng-model上使用'string'名称

时间:2014-07-30 17:23:20

标签: javascript html angularjs

在普通的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>

3 个答案:

答案 0 :(得分:3)

如果你真的想要连字符和空格,我可能会使用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>

控制器:

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;

查看:

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

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

答案 1 :(得分:2)

Angular上下文中的$ scope是一个对象。它指的是应用程序模型。

因此,

$scope.item_text = 'Hello';

$scope['item_text'] = 'Hello';

应该都有效。

但是,请注意 ng-model ,它只能用于表单元素。

使用上述任何声明,

<input type="text" ng-model="item_text">

将起作用

答案 2 :(得分:0)

尝试这样写

$scope.itemText={};

使用时应考虑在javascript中使用camelcase作为空格和破折号通常会导致太多问题