John M. John M. - 1 month ago 19
AngularJS Question

Trouble displaying data in AngularJS

I made a small angularjs application where the user picks a month and then the page displays the appropriate fly (as in fly fishing) to use. I can get part of it to work but not the other. Part that is working: when the user selects a month the app does display the correct fly to use. Part that is not working: I would like the display text to read: "The correct fly to use for [month name goes here] is : [name of fly goes here]."

Repeating what I said earlier, the second part of what I want displayed is working. I do get the correct fly name. It is the first part where I want it to repeat the selected month that I cannot figure out. Thank you.

JS

angular.module('myApp', ['ngRoute'])

.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/home', {
templateUrl: 'views/home.html',
controller: 'myController'
})
.when('/directory', {
templateUrl: 'views/directory.html',
//since this page requires a controller
controller: 'myController'
})
.otherwise({
redirectTo: '/home'
});

}]); //.config


angular.module('myApp')
.controller('myController', function($scope) {
$scope.dir_message = ("This is the directory page.");
$scope.months = [{monthName: 'January', flyName: 'Clouser Deep Minnow' },{ monthName: 'February', flyName: 'Woolly Bugger' },{ monthName: 'March', flyName: 'Zonker' }];
});


HTML

<p>Select a Month.</p>

<div ng-app="myApp">
<select ng-model="selectedItem">
<option ng-repeat="month in months" value="{{month.flyName}}">{{month.monthName}}</option>
</select>

<div ng-model="month">
<p>The correct fly to use for {{month.monthName}} is : {{selectedItem}}</p>
</div>

</div>

Answer

Use ng-options instead of ng-repeat. That will allow binding a month object (with its name and its fly name) to the selectedItem property.

  <select ng-model="selectedItem" ng-options="month as month.monthName for month in months">
    <option value=""></option>
  </select>

  <p>The correct fly to use for {{ selectedItem.monthName}} is : {{ selectedItem.flyName }}</p>

Note than ng-model on a div makes no sense.

Comments