具有隔离范围的AngularJS表单控制指令

时间:2017-04-23 11:27:20

标签: angularjs angularjs-directive

我有一个指令来呈现带有一些特定值的select元素。这是代码:

指令的模板:

<select id="{{name}}"
  class="form-control"
  ng-model="selectedOption"
  ui-jq="selectpicker"
  ui-options='{ iconBase: "famfamfam-flag", tickIcon: "fa fa-check" }'>
<option ng-repeat="o in data" value="{{o.id}}">{{o.label}}</option>

指令代码:

(function () {
appModule.directive('yesNoDeclineCombo', ['$timeout', 
function ($timeout) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: '/yesNoDeclineCombo.cshtml',
        scope: {
            selectedOption: '=?',
            name: '@'
        },
        link: function ($scope, element, attrs) {
            $scope.data = app.consts.yesNoDeclineData;
            $scope.data.unshift({ id: null, label: 'Not Assigned' });

            //refresh combo
            $timeout(function () {
                $(element).selectpicker('refresh');
            });

            $scope.$watch('selectedOption', function (newValue) {
                $timeout(function () {
                    $(element).selectpicker('refresh');
                }, 0);
            });
        }
    };
}
]);
})();

标记使用:

<yes-no-decline-combo selected-option="vm.specialDietId"
     ng-required="vm.isFieldRequired('SpecialDiet')" name="SpecialDiet">
</yes-no-decline-combo>

标记渲染:

<select id="SpecialDiet" class="form-control ng-pristine ng-untouched ng-isolate-scope ng-empty ng-invalid ng-invalid-required" ng-model="selectedOption" ui-jq="selectpicker" ui-options="{ iconBase: &quot;famfamfam-flag&quot;, tickIcon: &quot;fa fa-check&quot; }" selected-option="vm.specialDietId" ng-required="vm.isFieldRequired('SpecialDiet')" name="SpecialDiet" required="required" tabindex="-98">
<!-- ngRepeat: o in data --><option ng-repeat="o in data" value="" class="ng-binding ng-scope" selected="selected">Not assigned</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="1" class="ng-binding ng-scope">Yes</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="2" class="ng-binding ng-scope">No</option><!-- end ngRepeat: o in data --><option ng-repeat="o in data" value="3" class="ng-binding ng-scope">Decline To Answer</option><!-- end ngRepeat: o in data -->

我如何能够使指令将ng-model呈现为:

ng-model="vm.specialDietId"

而不是

ng-model="selectedOption"

我需要这种行为的原因是因为另一个属性指令读取了ngModel绑定的模型属性并执行了其他一些功能。

由于

1 个答案:

答案 0 :(得分:0)

我认为您可能会尝试将scope: {...替换为scope: true以与外部范围共享值。今天这被认为是坏习惯,但如果必须,它应该有效。当然,您还必须更改{{name}}绑定。