Button inside ng-repeat to update input in form

What I'm trying to do is update the input field from ng-repeat. I have ng-click on a button inside ng-repeat for each user. When you click on the button, it should update the value of the input field, which is outside of ng-repeat, but in the same controller. I just started using Angularjs, and it seems to me that something is missing here, but I just can not understand. Any help is much appreciated!

<div ng-app="MyApp"> <div ng-controller="Main"> <form name="myForm"> <input type="email" ng-model="rootFolders"> <button type="submit">Submit</button> </form> <span ng-repeat="user in users" style="float:left"> {{user.name}}<br> <button ng-click="rootFolders='{{user.login}}'">Load Email</button> </span> </div> </div> 

controller

 angular.module('MyApp', []); function Main($scope) { $scope.rootFolders = ' bob@go.com '; $scope.users = [ {id:0,name:'user1',login:' user1@go.com ',password:'123456'}, {id:1,name:'user2',login:' user2@go.com ',password:'123456'}, ] } 

Here is the fiddle: http://jsfiddle.net/DahDC/

+4
source share
2 answers

You need to create an ng-click action in scope and pass the current line to the user.

 <div ng-app="MyApp"> <div ng-controller="Main"> <form name="myForm"> <input type="email" ng-model="rootFolders"> <button type="submit">Submit</button> </form> <span ng-repeat="user in users" style="float:left"> {{user.name}}<br> <button ng-click="loadEmail(user);">Load Email</button> </span> </div> </div> angular.module('MyApp', []); function Main($scope) { $scope.rootFolders = ' bob@go.com '; $scope.users = [{ id: 0, name: 'user1', login: ' user1@go.com ', password: '123456' }, { id: 1, name: 'user2', login: ' user2@go.com ', password: '123456' }, ] $scope.loadEmail = function (user) { $scope.rootFolders = user.login; } } 

Give it a try. Fiddle

+9
source

I believe that since you are doing the job inside ng-click inside ng-repeat, it assigns the rootFolders property in the local area there (an instance using ng-repeat for each element). That way, you are actually assigning a new property in all local ng-repeat regions.

I edited your script to show this explicitly. Good learning point!

 <div ng-app="MyApp"> <div ng-controller="Main"> <form name="myForm"> <input type="email" ng-model="rootFolders"> {{ rootFolders }} <button type="submit">Submit</button> </form> <span ng-repeat="user in users" style="float:left"> {{user.name}}<br> <button ng-click="rootFolders = user.login">Load Email {{ user.login }}</button><br/> {{ rootFolders }} </span> </div> 

+1
source

Source: https://habr.com/ru/post/1493763/


All Articles