简体   繁体   中英

ng-model as value for ng-init input

I'm trying to figure out on how can I set the value of my input based on the ng-model of my another input, Here is what I did:

 angular.module('selectExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.register = { regData: { branch: {}, }, bloodbankchapters: [ {_id:'5c014c999cc48c3b0057988b', chapter_name:"AB"}, {_id:'5c014c999cc48c3b0057988c', chapter_name:"A"}, ], }; }]); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script> <div ng-app="selectExample" ng-controller="ExampleController"> <select ng-model="register.regData.branch" ng-options ="chapter.chapter_name for chapter in register.bloodbankchapters track by chapter._id"> <option ng-repeat="chapter in register.bloodbankchapters" >{{chapter.chapter_name}}</option> </select> <div>{{register.regData.branch.chapter_name}}</div> <input type="text" ng-model="register.regData.branch_name" name="branch_name" ng-init="register.regData.branch_name='{{register.regData.branch.chapter_name}}'"> </div> 

As you can see, my second input literally show {{register.regData.branch.chapter_name}} instead of showing chapter_name , How can I show the chapter_name in my second input?

There are slight changes in HTML. You can refer JsFiddle

<div ng-app="selectExample" ng-controller="ExampleController">

  <select ng-model="register.regData.branch" ng-options ="chapter.chapter_name for chapter in register.bloodbankchapters" ng-change="register.regData.branch_name=register.regData.branch.chapter_name">
    <option ng-repeat="chapter in register.bloodbankchapters" >{{chapter.chapter_name}}</option>
  </select>
  <div>{{register.regData.branch.chapter_name}}</div>

  <input type="text" ng-model="register.regData.branch_name" name="branch_name"> 

</div>

If I understand right, you need something like this? https://stackblitz.com/edit/angularjs-52l5k7

If you want to reuse your ng-model you should use ng-bind to bind data. https://docs.angularjs.org/api/ng/directive/ngBind

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM