如何将ng-options中的选定选项值绑定到控制器中对象的值?

时间:2017-09-01 17:24:28

标签: javascript angularjs arrays angularjs-directive ng-options

尝试更新ng-options中选项的当前选定值时遇到了一些麻烦。
我有一个包含一个对象的数组。该对象具有值为常量的“值”和“名称”属性。
我在带有select和ng-options的自定义指令中使用这个常量数组。这是指令html的一部分:

<select
    name="{{vm.name}}"
    ng-model="vm.model"
    ng-options="arrayObject.value as arrayObject.name for arrayObject in 
  vm.constantArrayofObject">
</select>

我以视图的形式使用此指令。

   <directive
     model=""
     form="someForm"
     name="someName">
   </directive>

在控制器的视图中,我有一个对象'controllerObject',它有一个对象数组作为属性,如下所示:

controllerObject.properties: [
   {
    value: "someValue",
    name: "someName"
   }
]

我必须将选定选项的值和名称绑定到controllerObject.properties数组中对象的值和名称,并将它们传递给update()函数。但我不知道如何在html视图中访问指令中的控制器对象。因为它已经在常量数组中显示对象的值。这就是为什么我没有在指令的模型属性中放置任何东西。如何连接两个对象数组并将所选值映射到控制器(和名称)中对象的值?
任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

使用隔离范围两个数据绑定“=”运算符共享选项数组的数据。为此,只需要一个带有controllerObject.properties数组的属性select-options。然后将它放在指令范围块内。所以要使用的指令可以是:

<mydirective field="fielddata" select-options="controllerObject.properties"></mydirective>

DDO:

app.directive('mydirective', function() {
  return {
    restrict: 'E',
    templateUrl: 'dirtemplate.html',
    scope: {
      field: "=",
      selectOptions: "="
    }, 
    link: function(scope, element, attrs) {

    }
  };
});

其中dirtemplate.html是:

<select
  name="{{field.name}}"
  ng-model="field.model"
  ng-options="arrayObject.value as arrayObject.name for arrayObject in selectOptions">
</select>

在视图控制器中定义fielddata&amp; controllerObject as:

app.controller('MainCtrl', function($scope) {
  $scope.fielddata = {
    name: "country",
    form: "someForm",
    model: ""
  };
  $scope.controllerObject = {};
  $scope.controllerObject.properties = [
   {
    value: "someValue",
    name: "someName"
   },
   {
    value: "Value1",
    name: "Name1"
   },
   {
    value: "Value2",
    name: "Name2"
   }
  ];
});

Working plunker