How do I get the ng-model of a select tag to get the initially-selected option?

前端 未结 6 1741
一个人的身影
一个人的身影 2021-01-13 06:41

I\'m pretty new to Angular, so I may be going about this all wrong...

I have a

相关标签:
6条回答
  • 2021-01-13 07:33

    I have created example for your problem in plnkr. Visit: plnkr.co/edit/rKyjijGWSL1IKy51b8Tv?p=preview

    0 讨论(0)
  • 2021-01-13 07:34

    I think that it will be good it you will use ng-options attribute of select tag. It's an angular directive which creates options according to Array of options. You can take a look at select documentation
    If you use your code - your function myFunctionForDeterminingWhetherValueIsSelected works twice for every option at initialization and once for every option item when you select some another option.

    Demo with your code: http://plnkr.co/edit/0IVNLHiw3jpz4zMKcB0P?p=preview

    Demo for select you could see at description of select directive.

    Update

    At first, to see when value is changed - you need to use ng-change attribute of select tag, like this:

    <select ng-model="mySelectedValue" 
      ng-options="myValue for myValue in someDynamicArrayOfValues"
      ng-change="myFunctionForDeterminingWhetherValueIsSelected()">
      <option value="">--</option>
    </select>
    

    Then, i don't know how does myFunctionForSettingSelectedValue look like, but there are 2 variants:

    • This function returns some value - then you need to use ng-init next way.

    Controller:

      $scope.someInitFunc = function () {
        return 'One';
      };
    

    HTML:

    <select ng-model="mySelectedValue" 
          ng-options="myValue for myValue in someDynamicArrayOfValues"
          ng-change="myFunctionForDeterminingWhetherValueIsSelected()"
          ng-init="mySelectedValue = someInitFunc()">
          <option value="">--</option>
    </select>
    
    • You set value of mySelectedValue in this function - then you do this.

    Controller:

    $scope.someInitFunc = function () {
      $scope.mySelectedValue = 'One';
    };
    

    HTML:

    <select ng-model="mySelectedValue" 
      ng-options="myValue for myValue in someDynamicArrayOfValues"
      ng-change="myFunctionForDeterminingWhetherValueIsSelected()"
      ng-init="someInitFunc()">
      <option value="">--</option>
    </select>
    

    I have created an example which implements the first version of using ng-init. When new value is selected - it's printed to console.

    Also, i moved options to the options.json file. So options are initialized just after ajax request was finished. Everything works great.

    Demo: http://plnkr.co/edit/pzjxxTnboKJXJYBGcgNb?p=preview

    Update 2

    Hello again. I think you don't need to have any ng-init according to your requirements. You can just initiate values of your model when http request is finished. Also i don't understand why do you need ng-change function in this case.

    Here is modified code you need from your plunk where values of ng-models are initiated after options are loaded.

    JavaScript:

    .controller('MainCtrl', function($scope, $http) {
      $scope.someStaticArrayOfValues = ['One', 'Two', 'Three'];
      $scope.mySelectedValues = {};
      $http.get('options.json').then(
        function (response) {
          $scope.someDynamicArrayOfValues = response.data;
          for (var i = 0; i < $scope.someStaticArrayOfValues.length; ++i) {
            $scope.someDynamicArrayOfValues.some(function (value) {
              if (value.substring(0, $scope.someStaticArrayOfValues[i].length) === $scope.someStaticArrayOfValues[i]) {
                $scope.mySelectedValues[$scope.someStaticArrayOfValues[i]] = value;
                return true;
              }
            });
          }
        },
        function (response) {
          console.log('ERROR!');
        }
      );
    });
    

    HTML:

      <body ng-controller="MainCtrl">
        <p>Hello {{name}}!</p>
    
        <div ng-show="someDynamicArrayOfValues">
          <ul>
            <li ng-repeat="staticValue in someStaticArrayOfValues">
              {{staticValue}} - 
              <select ng-model="mySelectedValues[staticValue]" 
                ng-options="myValue for myValue in someDynamicArrayOfValues">
                <option value="">--</option>
              </select>
              <h2>{{mySelectedValues[staticValue]}}</h2>
            </li>
          </ul>
        </div>
      </body>
    

    Demo: http://plnkr.co/edit/9Q1MH0esGE1SIJa0m2NV?p=preview

    0 讨论(0)
  • 2021-01-13 07:35

    You can try to set the initial value of mySelectedValue in your Controller like so:

    $scope.mySelectedValue = '';
    
    0 讨论(0)
  • 2021-01-13 07:37

    It works a whole lot better when you use ng-options on your select element instead of nesting option with ng-repeat.

    https://docs.angularjs.org/api/ng/directive/select

    Then you are capable of setting the ng-model with ng-init.

    0 讨论(0)
  • 2021-01-13 07:40

    You are going about it the reverse way. ng-model reflects the state of the <select> and is two-way bound.

    You just need to set your mySelectedValue to what you want <select> to select first, and no other tricks are required.

    So, in the controller, do something like the following:

    $scope.mySelectedValue = someDynamicArrayOfValues[0];
    

    And remove the ng-selected and the <option ng-repeat...> from <select>:

    <select ng-model="mySelectedValue" 
            ng-options="value for value in someDynamicArrayOfValues">
        <option value="">--</option>
    </select>
    
    0 讨论(0)
  • 2021-01-13 07:41

    Here is a modified plunker that works as intended: http://plnkr.co/edit/Y8OSvmrG3u0XjnCU3ah5?p=preview.

    The main change was using ng-if in place of ng-show. This forces angular to recompile/link the html whenever it is rendered:

    <div ng-if="someDynamicArrayOfValues">
    ...
    </div>
    

    Also ng-change, from the original plunker, shouldn't be necessary, and there were a couple of typos fixed.

    0 讨论(0)
提交回复
热议问题