Search code examples
javascriptangularjsangularjs-factory

AngularJS Factory Info inconsistent


I have a factory that contains an array of objects. Each object contains info about an employee, like this:

DataFactory:

app.factory('DataFactory', function(){ 
    return [
        { 
            'name': 'John Smith',
            'shifts':[ //this might need to be {}
                    {'start':new Date(2014, 06, 25, 1, 30),
                    'end': new Date(2014, 06, 25, 22, 30)
                    },
                    {'start':'/*somedate*/',
                    'end': '/*someDate*/'
                    }
            ]
        }
    ];
});

And I am trying to set a value in a factory called CurrentUser based on which user the person using the app selects.

CurrentUser:

app.factory('CurrentUser', ['DataFactory', function(DataFactory){
    var service = {};
     service.indexVal;
    service.user = DataFactory[service.indexVal];
    return service;
}]);

HTML:

<select ng-model="CurrentUser.indexVal">
    <option ng-repeat="employee in DataFactory" value="{{$index}}">
        {{employee.name}}
    </option>
</select>

Current User: {{CurrentUser.user.name}}<br />

However, with this, there is no name value. It won't display "john smith" after selecting the name.

When I leave it as CurrentUser.user, rather than displaying the whole object of the user, it displays the indexVal.

How do I make it show the name?


Solution

  • Use ng-options if you want to bind to a model value:

    <select ng-model="CurrentUser.user" ng-options="employee as employee.name for employee in DataFactory">
    </select>
    
    Current User: {{CurrentUser.user.name}}<br />