beingalex beingalex - 5 months ago 25
AngularJS Question

Set value of input depending on element clicked in Angular

I have made the following plunker:

https://plnkr.co/edit/Ff2O2TGC4WLaD62fJmvA?p=preview

I would like the value of the input to be the

item.name
clicked.

Here is the code:

<body ng-app="myApp">

<div ng-controller="MyController">
<ul ng-repeat="item in collection">
<li ng-click="edit('{{item.name}}')">{{item.name}}</li>
</ul>
</div>

<input name="myinput" ng-model="myinput" />

</body>


Js:

var app = angular.module('myApp', [])

.controller('MyController', function($scope, $http) {

$scope.collection = [
{name:'foo'},
{name:'bar'},
{name:'foobar'},
{name:'barfoo'},
];

$scope.edit = function(current_name) {

this.myinput = current_name;

console.log(current_name);

}

})

Answer

So there are a few problems here. The first is how you're passing item.name into the edit function. Instead of edit('{{item.name}}') it should simply be edit(item.name).

The next is this.myinput in the script.js isn't going to work; it needs to be $scope.myinput.

Finally, the input in the markup needs to be inside the div that defines the controller.

I've modified the Plunkr to work: https://plnkr.co/edit/mslpklTaStKEdo64FpZl?p=info

Comments