user3761308
user3761308

Reputation: 791

angularjs - Update ng-model value from controller?

View 1:

<div ng-controller="ctrl1">
    <button ng-click="goToExtendedForm({'name':'aaa'})">
    </button>
</div>

ctrl1:

    $scope.selectedList = {
        name: ""
    };

    $scope.goToForm = function(e) {
        $scope.selectedList.name = e.name;
        $state.go('view2');
        console.log(e); // prints updated value
    };

View 2:

<div ng-controller="ctrl1">

<input
        id="name"
        name="name"
        type="text"
        ng-model="selectedList.name"
        ng-readonly="true"
/>
</div>

But the input box is always empty, even though to get to the view the goToForm() is called. Why doesn't it update the HTML value? Views are changed with ui.router's $state.

Upvotes: 0

Views: 4534

Answers (3)

Dushyantha
Dushyantha

Reputation: 217

Try this ;

HTML Code

  <div ng-app>
      <div ng-controller="ClickToEditCtrl">
        <input
                                id="name"
                                name="name"
                                type="text"
                                ng-model="selectedList.name"
                                ng-readonly="true"
                        />
                        <button ng-click="goToForm(testUserDetails)" >Go To</button>

                        </button>
      </div>
    </div>

Define controller like this;

function ClickToEditCtrl($scope) {
  $scope.selectedList = {
        name: ""
    };
$scope.testUserDetails ={
        name: "nimal"
}
    $scope.goToForm = function(e) {
        $scope.selectedList.name = e.name;
        console.log(e); // prints updated value
    };
}

Upvotes: 0

Aleksey Solovey
Aleksey Solovey

Reputation: 4191

From your description, your code is supposed to work. Check if you are passing the right parameter into the function. Here is a working demo:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.selectedList = {
    name: ""
  };

  $scope.goToForm = function(e) {
    $scope.selectedList.name = e.name;
    console.log(e); // prints updated value
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">

  <button ng-click="goToForm({'name':'aaa'})">Change</button>
  <br>
  <input type="text" ng-model="selectedList.name" ng-readonly="true" />

</div>

Upvotes: 3

Sajjad Shahi
Sajjad Shahi

Reputation: 602

Try adding $scope.$apply() at the end of your $scope.goToForm function

Upvotes: 0

Related Questions