Qwerty Qwerty - 5 months ago 56
AngularJS Question

Assign value to anchor tag - angularjs

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)?

Answer

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"

    }]
  }
});

Working DEMO

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>