在我的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>
当用户点击&#34;点击&#34;在输入字段旁边的链接,我想访问我的控制器中的输入字段来设置/获取该字段值。以下是我的控制器代码
$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
我无法访问&#34; color&#34;模型,如果在视图中重复。所以我试着生成随机模型名称(用模型中的颜色连接c.id),我尝试了几种方法来实现这一点,但没有运气。
有没有办法生成随机的ng-model名称?
OR
有没有办法访问输入字段的模型&#34; Click&#34;单击链接?
答案 0 :(得分: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
});