Kresent Kresent - 1 year ago 141
AngularJS Question

Angular changing dataset without $watch

I have an array of objects like this

UserList = [

And html select like this

<select ng-model="data.selectedUser">

<option ng-repeat="item in data.items" value="{{}}">{{}}</option>



Inside my controller I use

$ = {};
$ = 0;
$ = UserListModel.items;
$ = UserListModel.items[$].phone;

Is there a way to update selected user phone on selectedUser change without using $watch and stuffing the "$" inside it?

Answer Source

Imagine you have a data like this:

  $ = {};
  //set the data
  $ [{
    id: 1,
    name: "cyril",
    phone: "1234567"
  }, {
    id: 2,
    name: "josh",
    phone: "1237"
  }, {
    id: 3,
    name: "sim",
    phone: "4567"
  //selected hold the object that is selected in the selectbox.
  $scope.selected = $[0];

Your html will look like this below so now when you select the new user from the list it will be updated in the model selectedItem, the selectedItem has the phone number in it (so you dont need a watch to update phone number seperately as you doing).

 <body ng-controller="MainCtrl">
    <p>selected item is : {{selectedItem}}</p>

    <p> name of selected item is : {{}} </p>

    <select ng-model="selectedItem" ng-options=" for item in items track by"></select>


working example here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download