繁体   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