2017-09-01 100 views
1

我嘗試更新ng選項中選項的當前選定值時遇到一些麻煩。
我有一個包含一個對象的數組。該對象具有值「恆定」的「值」和「名稱」屬性。
我正在使用select和ng-options的自定義指令中使用此常量數組。這是該指令的html的一部分:如何將ng選項中的選定選項值綁定到控制器中的對象值?

<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

使用隔離範圍雙向數據綁定「=」運算符共享選項數組的數據。爲此,只需使用controllerObject.properties數組獲得一個更多屬性選擇選項。然後把它放在指令的範圍塊內。所以指令要使用可以是:

<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 & controllerObject爲:

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

+0

謝謝!這解決了我的問題! – Julsy

+0

@Julsy很高興幫助:) – Shantanu

相關問題