0

在我的 angular.js 项目中,我有一个包含输入字段的循环

<input type="text" ng-model="myColour">
<div ng-repeat="c in colors">
    <input type="text" ng-model="colour">
    <a href ng-click="asd(colour)">Click</a>
</div>

当用户单击输入字段旁边的“单击”链接时,我想访问控制器中的该输入字段以设置/获取该字段值。以下是我的控制器代码

$scope.colors = [
    {id: 1, name: 'black', shade: 'dark'},
    {id: 2, name: 'white', shade: 'light'},
    {id: 3, name: 'red', shade: 'dark'},
    {id: 4, name: 'blue', shade: 'dark'},
    {id: 5, name: 'yellow', shade: 'light'}
];

$scope.asd = function(data){
    console.info(data);
    console.info($scope.myColour);
    console.info($scope.colour);
};

这给了我

colour input field data
my colour input field data
undefined 

如果在视图中重复,我将无法访问“颜色”模型。所以我尝试生成随机模型名称(将 c.id 与模型中的颜色连接起来),我尝试了几种方法来实现这一点,但没有运气。

有没有办法生成随机的 ng-model 名称?

或者

有什么方法可以访问单击“单击”链接的输入字段模型?

4

1 回答 1

1

尝试这样的事情:

<div ng-repeat="c in colors">
    <input type="text" ng-model="c.colour">
    <a href ng-click="asd(c.colour)">Click</a>
</div>

与 JS:

// your collection
$scope.colors = [
    {id: 1, name: 'black', shade: 'dark'},
    {id: 2, name: 'white', shade: 'light'},
    {id: 3, name: 'red', shade: 'dark'},
    {id: 4, name: 'blue', shade: 'dark'},
    {id: 5, name: 'yellow', shade: 'light'}
];

// add a new key called 'colour' on your colors which will be the model
angular.forEach($scope.colors, function(value, key){
   $scope.colors[key]['colour'] = ""; // match node in html
});
于 2014-04-30T15:03:04.837 回答