加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在指令中使用ng-options并从注入的服务获取选项数

发布时间:2020-12-17 17:18:21 所属栏目:安全 来源:网络整理
导读:我创建了一个包含选择输入字段的自定义指令. 我正在使用ng-options填充选择选项,我现在使用绑定到隔离范围的options属性传递选项的数据.见下文. script recManagerApp.directive(myDirective,function () { return { restrict: 'E',templateUrl: '/templates
我创建了一个包含选择输入字段的自定义指令.

我正在使用ng-options填充选择选项,我现在使用绑定到隔离范围的options属性传递选项的数据.见下文.

<script>
  recManagerApp.directive(myDirective,function () {
    return {
      restrict: 'E',templateUrl: '/templates/directives/mydirective.html',scope: {
        mySelectedValue: "=",options : "="
      }
    };
  });
</script>

<my-directive my-selected-value="usersValue" options="myDataService.availbleOptions"></my-directive>

<div>
  <select data-ng-model="mySelectedValue" data-ng-options="item for item in options">
    <option value="">Select something</option>
  </select>
</div>

上述工作按预期工作,正确填充选项,选择正确的值并与父作用域中的属性进行双向绑定.

但是,我宁愿不使用my-directive元素上的属性传入选项,而是注入可以为ng-options提供数据的服务(myDataService).但是,当我尝试这种(各种方式)时,尽管服务正确注入且数据可用,但没有创建任何选项.有谁能建议这样做的方法?

recManagerApp.directive(myDirective,function (myDataService) {
    return {
        restrict: 'E',scope: {
            mySelectedValue: "=",options : myDataService.availableOptions
        }
    };
});

谢谢

解决方法

在我看来,你有几个选择(如评论中所指出的):

1.为指令创建控制器

在你指令的模板中,使用一个控制器,即

<div ng-controller="SelectController">
  <!-- your select with the ngOptions -->
</div>

并将SelectController创建为常规控制器:

var app = angular.module("app.controllers",[])

app.controller("SelectController",['$scope','myDataService',function(scope,service) {
  scope.options = service.whatEverYourServiceDoesToProvideThis()
}]);

你也可以给你的指令一个控制器,它的工作方式是一样的:

recManagerApp.directive(myDirective,function () {
    return {
        restrict: 'E',},controller: ['$scope',service) {
          scope.options = service.whatEverYourServiceDoesToProvideThis()
        }]
    };
});

2.将其注入指令并在链接中使用它

recManagerApp.directive(myDirective,scope: {
            mySelectedValue: "="
        },link: function(scope) {
          scope.options = myDataService.whatEverYourServiceDoesToProvideThis()
        }
    };
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读