Ahmad Shli
Ahmad Shli

Reputation: 69

Update ng-model or $scope variables from controller

I am having some difficulties in updating textbox using Angularjs with ASP.Net MVC. I have <div> tag displaying ng-model... When I click on Edit button, a textbox appears so I can edit the name that was displayed in the <div>...

I am using different ng-models in the div and the input because I don't want direct binding...

So, I am actually having two questions:

1- If I will use the same ng-model in both sides, what if I wanted to cancel editing after entering text already?? The text will be changed anyway, is there a way to undo the change??

2- If not, then my second question, I need your help in updating the textbox input to get the value of the div when I click on Edit.

Below is my code:

My view:

<div ng-show="!nameElements" class="item_list">{{u.fName}}</div>
<div ng-show="nameElements">
     <input type="text" id="ufn" ng-model="userfName">
     <a href="javascript:void(0)" ng-click="updateUserName()"><i class="fa fa-floppy-o fa-lg" aria-hidden="true"></i></a>
</div>

My angular controller:

$http.get('/Home/GetUser')
    .then(function (response) {
        $scope.users = response.data;
        $scope.itmNo = response.length;
        $scope.userfName = response[0].fName;//This is not working!!
        }
    })
    .catch(function (e) {
        console.log("error", e);
        throw e;
    })
    .finally(function () {
        console.log("This finally block");
    });

So, the issue is, I am not able to change/update the ng-model from my controller.

I hope my question is clear

Upvotes: 0

Views: 656

Answers (1)

Duncan
Duncan

Reputation: 95782

It seems to me likely that you were previously using .success(function (response) {...}) and changed it to .then(function(response) {...}.

The parameters for .success() and .then() callbacks are not the same. The first parameter passed to the .success() calback is the response.data value passed to .then().

Your code should probably be:

$http.get('/Home/GetUser')
    .then(function (response) {
        var data = response.data
        $scope.users = data.data;
        $scope.itmNo = data.length;
        $scope.userfName = data[0].fName;
        }
    })

Upvotes: 1

Related Questions