Angularjs在加载模板时分配元素的ngmodel

Angularjs在加载模板时分配元素的ngmodel,angularjs,Angularjs,我有以下指示: app.directive("mydirect", function () { return { restrict: "E", templateUrl: "mytemplate.html", } }); mytemplate.html中的模板是: <input ng-model="name{{comment.ID}}" ng-init="name{{comment.ID}}={{comment.Name}}" />

我有以下指示:

app.directive("mydirect", function () {
    return {
        restrict: "E",
        templateUrl: "mytemplate.html",
    }
});
mytemplate.html
中的模板是:

<input ng-model="name{{comment.ID}}" ng-init="name{{comment.ID}}={{comment.Name}}"  />

我多次加载模板,每次我都想更改分配为
ng model
的变量,例如
ng model=“name88”
(for
comment.ID==88

但所有加载的模板都具有相同的值


但是,当我更改
comment.ID
时,所有插入的模板都将成为最后一个更改的ID。

首先,您不能在
ng model
中放置表达式,如
name{{comment.ID}
——它需要分配给一个变量

因此,让我们将模板更改为:

<input ng-model="comment.ID" ng-init="comment.ID = comment.Name">
这很方便-
comment
既是
ng repeat
中使用的变量,也是指令模板中使用的变量。但这不是太可重用。如果要更改
注释
对象的结构,该怎么办?如果您想并排放置多个指令,而不使用为
ng repeat
的每次迭代创建的子作用域,并为每个指令分配不同的
comment
对象,该怎么办

为此,应该为指令使用隔离作用域。您应该阅读更多关于它的内容,但简而言之,它的工作方式是允许您指定一个内部变量,该变量将在模板中使用,并将其绑定到分配给该指令所声明的元素的某个属性的任何变量

这是这样做的:

app.directive("mydirect", function () {
    return {
        restrict: "E",
        scope: {
           // this maps the attribute `src` to `$scope.model` within the directive
           model: "=src" 
        },
        templateUrl: '<input ng-model="model.ID">',
    }
});
然后你可以这样使用它:

<mydirect src="comment1"></mydirect>
<mydirect src="comment2"></mydirect>

或者,如果您有一个注释数组,无论是静态创建注释还是从服务调用加载注释,您都可以这样做:

<div ng-repeat = "comment in comments">
  <mydirect src="comment"></mydirect>
</div>


试试这个:name[{{comment.ID}]是的,这样的模板是无效的-你不能对变量名称使用{{}}你是说你想动态地确定ng模型绑定到什么?有时是
$scope.name88
,有时是
$scope.name53
?你能更全面地描述一下你想做什么吗?这个指令是如何使用的?想想这个方法@kaneda,好的。你为什么要这样做?你想完成什么?太好了,这是工作:D。非常感谢。对于每个新注释,我增加一个变量nbComment:eval('$scope.comment'+nbComment+'=response.data');并传递到编译$compile(“”)($scope)@kaneda,这可能不是正确的方法。使用
ng repeat
方法,只需
。将新的
注释推入数组中。
<mydirect src="comment1"></mydirect>
<mydirect src="comment2"></mydirect>
<div ng-repeat = "comment in comments">
  <mydirect src="comment"></mydirect>
</div>