Get old value and new value from dropdown

浪尽此生 提交于 2019-11-30 03:54:18

问题


I'm trying to simply get the previous value, and the newly selected value from a drop-down. In this example, the drop-down is pre-populated with the current group the user is assigned.

When the drop-down is changed, I want to be able to return the old value and the new value. I can already get the old value, but I don't know how to return the new value.

Controller Code:

// User Object
userAccess = [{"user_name":"dodsosr11",
                  "group_level":1,
                  "user_id":500,
                  "group_id":10,
                  "group_name":"Conferences_Admins"},
              {"user_name":"keatikj09",
                  "group_level":1,
                  "user_id":250,
                  "group_id":10,
                  "group_name":"Conferences_Admins"},
              {"user_name":"malinag10",
                  "group_level":1,
                  "user_id":492,
                  "group_id":10,
                  "group_name":"Conferences_Admins"}];

//Group Object
groupAccess = [{"group_name":"Conferences_Admins",
                   "id":10,
                   "level_id":1},
               {"group_name":"ticket_sales",
                   "id":59,
                   "level_id":3},
               {"group_name":"Web Developers",
                   "id":1,
                   "level_id":1}];


$scope.reassignUser = function(){
    var oldGroup = this.user.group_id;
    var newGroup = ?????

};

HTML:

<tr ng-repeat="user in userAccess">
    <td>{{ user.user_name}}</td>
    <td>
        <select ng-change="reassignUser()" 
                ng-model="user.group_name" 
                ng-options="g.group_name as g.group_name for g in groupAccess">
        </select>
    </td>
</tr>

I've created a fiddle here using the watch example that was provided in the first response below. http://jsfiddle.net/LHz9D/1/


回答1:


Try like this

View

<select ng-model="selected" ng-change="change(selected, {{selected}})">

JS

$scope.change = function(newObj, oldObj){
   console.log(newObj);
   console.log(oldObj);
}



回答2:


you could use ng-click, since click happens before change you could there register the old value like this

<select ng-model="selected" ng-change="change(selected, oldValue)" ng-click="oldValue = selected">

and in the controller

$scope.change = function(newValue, oldValue){
    //do if's in case you use null or empty values
    if ( oldValue ) {
        //do something
    }   
    if ( newValue ) {
        //do something
    }
}



回答3:


Do it like this:

$scope.$watch('user.group_name', function(newValue, oldValue){

});

No need to use ng-change any more



来源:https://stackoverflow.com/questions/21909163/get-old-value-and-new-value-from-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!