Reputation: 2423
User sees a list of options (eg: 1.Apple ; 2.Banana ; 3.Mango). There is a textbox where user types in the desired option and clicks send to proceed further.
Existing Setup:
HTML:
<p ng-repeat="opt in objHistory.OptionItems track by $index">
{{ opt.SortOrder }}. {{ opt.OptionName }}
</p>
<textarea ng-model="userInput"></textarea>
<a href="javascript:;" ng-click="GetNextItem()">Send</a>
JS:
$scope.GetNextItem = function () {
alert($scope.userInput);
//some code
}
The above code is working good. But now I have changed the options to anchor tags, so user can click on them, instead of typing and the same flow follows.
New HTML:
<p ng-repeat="opt in objHistory.OptionItems track by $index">
<a href="javascript:;"
ng-model = "userInput"
ng-init="userInput=opt.SortOrder"
ng-click="GetNextItem()">{{ opt.SortOrder }}. {{ opt.OptionName }}
</a>
</p>
I get undefined
in the alert now. Where am I going wrong? Can the same ng-model
variable name be used multiple times (I'm using it for the textbox
and also the anchor
tags)?
Upvotes: 1
Views: 7897
Reputation: 18566
You are trying to read the set value before Angular is done assigning.
HTML:
<p ng-repeat="opt in objHistory.OptionItems track by $index">
<a href="javascript:;"
ng-model = "userInput"
ng-init="init(opt)"
ng-click="GetNextItem()">{{ opt.SortOrder }}. {{ opt.OptionName }}
</a>
</p>
<textarea ng-model="userInput"></textarea>
Controller:
angular.module("app",[]).controller("MainController", function($scope) {
$scope.GetNextItem = function () {
alert($scope.userInput);
//some code
};
$scope.init = function(opt) {
$scope.userInput = opt.SortOrder; // set it in the init method
};
$scope.objHistory = {
OptionItems: [{
SortOrder : "1",
OptionName: "Hi"
}, {
SortOrder : "2",
OptionName: "Hi"
}]
}
});
Update based on comment:
$scope.GetNextItem = function (opt) {
$scope.userInput = opt.SortOrder;
//some code
};
Now in your HTML:
<p ng-repeat="opt in objHistory.OptionItems track by $index">
<a href="javascript:;"
ng-click="GetNextItem(opt)">{{ opt.SortOrder }}. {{ opt.OptionName }}
</a>
</p>
Upvotes: 1
Reputation: 180
ng-model
cannot be used on anchor tags unless you have an input field or a custom directive. According to docs:
The
ngModel
directive binds aninput
,select
,textarea
(or custom form control) to a property on the scope usingNgModelController
, which is created and exposed by this directive.
Why are you using ngModel
on anchor tags?
Sorry not enough rep to comment
Upvotes: 2