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

前端之家收集整理的这篇文章主要介绍了angularjs – 在指令中使用ng-options并从注入的服务获取选项数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我创建了一个包含选择输入字段的自定义指令.

我正在使用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()
        }
    };
});

猜你在找的Angularjs相关文章