Angular: Empty Fiddle
http://angularjs.org/
HTML
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<div ng-controller="MyDisplayCtrl">
<select ng-model="item" ng-options="i.name for i in items">
</select>
</div>
<div ng-controller="MyManageCtrl">
<div ng-repeat="item in items">
{{item.name}}
</div>
<input type="button" ng-click="addItem()" value="add item" />
</div>
JavaScript
var myApp = angular.module('myApp',[]);
/**************************************************/
// //
// when adding an item, I would like //
// to select the new item in the dropdown //
// //
// I have tried updating the ItemStore //
// service's currentItem attribute, but //
// this does not update the dropdown, and //
// dropdowns do not seem capable of binding //
// to a function. //
// //
// how do I update a dropdown when using //
// a service to supply the data //
// //
/**************************************************/
function MyManageCtrl($scope, ItemStore) {
$scope.items = ItemStore.items;
$scope.addItem = function(){
// setting the ItemStore's current item. Called on button click.
ItemStore.currentItem = ItemStore.addItem();
}
}
MyManageCtrl.$inject = ['$scope', 'ItemStore']
function MyDisplayCtrl($scope, ItemStore) {
$scope.items = ItemStore.items;
$scope.item = ItemStore.currentItem;
// ng-model cannot bind to function on select element?
$scope.getItem = function(){
return(ItemStore.currentItem);
}
}
MyDisplayCtrl.$inject = ['$scope', 'ItemStore']
myApp.factory('ItemStore', function(){
var items = [{name: ' first item '}];
var addItem = function(){
newItem = {name: 'item '+items.length};
items.push(newItem);
return(newItem);
};
var currentItem = items[items.length-1];
return({
currentItem: currentItem,
items: items,
addItem: addItem});
});