簡體   English   中英

從沒有ngOptions的指令中設置angular.js控制器變量

[英]Setting angular.js controller variable from within a directive without ngOptions

我想將所選選項的文本設置為控制器變量,就像ngModel如何對所選選項的value屬性進行設置一樣。

<div ng-controller="Subjects as ctrl">
  <select ng-model="ctrl.model.fieldId" text-model="ctrl.model.fieldName">
    <option value="1">yes</option>
    <option value="2">no</option>
  </select>
</div>

我如何將ctrl.model.fieldName設置為yes ,例如,如果選擇的第一個選項不是指令中的函數? 該指令必須與ngModel一起使用。

我想要一種不使用ngOptions的方法,因為我的javascript中沒有任何值數組,盡管我可以解析HTML並創建一個。

到目前為止,該指令:

(function () {
    angular
        .module('app')
        .directive('TextModel', TextModel);
    function TextModel($compile) {
        return {
            restrict: 'A',
            link: function ($scope, elem, attr) {
                elem.on('change', selectChanged);
                $scope.$on('$destroy', function () {
                    elem.off('change', selectChanged);
                });
                function selectChanged() {
                    var selectedText = elem.find('option:selected').text();
                    //YAY! I have the selected option's text
                    console.log(selectedText);
                    //now how can I set ctrl.model.fieldName = selectedText ??
                }
            }
        };
    };

})();

您不需要其他指令。

最好將您的選擇選項綁定到{key:value}數組或任何其他對象數組

看到這里: https : //docs.angularjs.org/api/ng/directive/ngOptions

然后,您可以將ng-model綁定到所選項目。

$scope.items = [
    {key : 1 , value : 'yes'},
    {key : 2 , value : 'no'}
]

<select ng-model="selectedItem" ng-options="item as item.value for item in items"></select>

Jsfiddle上的演示

更新:

如果要為此使用自己的指令,則可以使用如下所示的隔離范圍:

function TextModel($compile) {
    return {
        restrict: 'A',
        scope : {
            'textModel' : '='
        },
        link: function (scope, elem, attr ) {
            elem.on('change', selectChanged);
            scope.$on('$destroy', function () {
                elem.off('change', selectChanged);
            });
            function selectChanged() {

                var selectedText = $(elem).find('option:selected').text();
                //YAY! I have the selected option's text

                //now how can I set ctrl.model.fieldName = selectedText ??
                scope.textModel = selectedText;
            }
        }
    };
};

順便說一句,您的指令設置器應為:

.directive('textModel', TextModel);

代替 :

.directive('TextModel', TextModel);

Jsfiddle上的演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM