使用Angularjs从后端获取选定的选项

时间:2017-03-09 05:55:49

标签: javascript angularjs symfony

如何在后端(Symfony)上选择启用我的选择选项。现在我初始化我的选择(ng-model="myselect"示例),如ng-init="myselect='0'" 我需要在ng-init中设置实际选择的选项,但如果我删除ng-init指令,则会创建值为? undefined:undefined ?的空选项。 我该怎么办?

2 个答案:

答案 0 :(得分:1)

<div ng-app="myapp">
  <fieldset ng-controller="FirstCtrl">
       <select 
        ng-options="p.id as  p.first + ' ' + p.last for p in people"
        ng-model="selectedPerson"></select>

    {{ selectedPerson }}
</fieldset>

 var myapp = angular.module('myapp', []);
 myapp.controller('FirstCtrl', function ($scope) {
 $scope.selectedPerson = 2;
 $scope.people = [
    { id: 1, first: 'John', last: 'Rambo', actor: 'Silvester' },
    { id: 2, first: 'Rocky', last: 'Balboa', actor: 'Silvester' },
    { id: 3, first: 'John', last: 'Kimble', actor: 'Arnold' },
    { id: 4, first: 'Ben', last: 'Richards', actor: 'Arnold' }
    ];
 });

这是你的期望.. 另请查看此链接http://jsfiddle.net/kaehejgo/

答案 1 :(得分:0)

我能够赢得这个问题。

使用我自己的函数将vanilla html选择转换为角度模型的匿名函数将字符串转换为对象引用。

(function(){
    window.selectControl = [];
    var selects = document.querySelectorAll(".filter__select_range");
    selects.forEach( function(elem, index) {
      var _elem = angular.element(elem);

      if (elem.querySelector("[selected]") !== undefined) {
        window.selectControl[_elem.attr("data-model")] = elem.querySelector("[selected]").value;
        _elem.attr({
          "ng-model": _elem.attr("data-model"),
          "ng-change": _elem.attr("data-change"),
          "ng-init": _elem.attr("data-model") + "='"+ _elem.find('option:selected').val() +"'",
        });

        _elem.removeAttr('data-model').removeAttr('data-change');
        stringToPath($scope, _elem.attr('ng-model'), elem.querySelector("[selected]").value);
      }
    });
  })();

stringToPath功能

function stringToPath(obj, str, val) {
    str = str.split(".");

    for (var i = 0; i < str.length; i++) {
      if (i != str.length-1 && str[i] != '') {
        if (typeof obj[str[i]] !== "object") {
          obj[str[i]] = {}
        }
        stringToPath(obj[str[i]], str.splice(1).join("."), val);
      }
      else {
        obj[str[i]] = val;
      }
    }
    return obj;
}

我选择的一种twig语法

{{- form_widget(form, {'attr': attr|merge({'class': 'filter__select filter__select_range', 'data-model': 'FilterCollection.range.area.min', 'data-change': "checkSelectedFilters();"})}) -}}