ng-model作为ng-init输入的值

时间:2019-01-18 12:00:54

标签: javascript angularjs mean-stack

我试图弄清楚如何根据另一个输入的ng-model设置输入的值,这是我所做的:

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>

如您所见,我的第二个输入从字面上显示{{register.regData.branch.chapter_name}}而不是显示chapter_name,我如何在第二个输入中显示Chapter_name?

2 个答案:

答案 0 :(得分:2)

HTML稍有变化。您可以参考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>

答案 1 :(得分:0)

如果我理解正确,您需要这样的东西吗? https://stackblitz.com/edit/angularjs-52l5k7

如果要重用ng-model,则应使用ng-bind绑定数据。 https://docs.angularjs.org/api/ng/directive/ngBind