【问题标题】:Angular Js custom directive for master data drop down主数据下拉的Angular Js自定义指令
【发布时间】:2018-04-23 22:14:56
【问题描述】:

Angular JS 新手,

我尝试使用来自 Web 服务的数据为下拉菜单定义自定义指令。

现在尝试处理一些静态数据但无法正常工作。

app.directive("deviceBranch", function(){
    return {
        templateUrl : 'resources/view/template/device-branch-list.html',
        controller : function($scope) {
            $scope.listBranch = [{
                deviceBranchId:"id1",
                deviceBranchName:"value1"
            },{
                deviceBranchId:"id2",
                deviceBranchName:"value2"
            },{
                deviceBranchId:"id3",
                deviceBranchName:"valkue3"
            }]
        }
    }
});

在模板中添加了“选择” -

ng-options="service.deviceBranchId as service.deviceBranchName for service in listBranch"

这就是我使用指令的方式

<device-branch></device-branch>

选择已填充,但没有可用选项。

请帮忙。

【问题讨论】:

  • 我想从网络服务中填充选项
  • 你能发布你的模板吗?甚至更好的 pker 重现您的问题

标签: html angularjs angularjs-directive


【解决方案1】:

看起来您只是在模板中缺少了一个 ng-model。下面是一个工作示例的链接。

<select ng-options="service.deviceBranchId as service.deviceBranchName for service in listBranch" ng-model="selected"></select>

您还可以将 $http 注入指令中以从 Web 服务获取数据。

app.directive("deviceBranch", function($http){
  return {
    templateUrl : 'device-branch-list.html',
    scope: {
      ngModel: '='
    },
    controller : function($scope) {
        $scope.listBranch = [{
            deviceBranchId:"id1",
            deviceBranchName:"value1"
        },{
            deviceBranchId:"id2",
            deviceBranchName:"value2"
        },{
            deviceBranchId:"id3",
            deviceBranchName:"valkue3"
        }]
    },
    link: function($scope, element, attrs){
      //var url = ""
      //$http.get(url).then(function(response){
      // $scope.listBranch = response;
      //})
    }
  }
});

这是模板 (device-branch-list.html):

<select ng-options="service.deviceBranchId as service.deviceBranchName for service in listBranch" ng-model="ngModel">

https://plnkr.co/edit/essg24GsrhSKwqXO578p?p=preview

【讨论】:

  • 感谢您的回答,但我想提供自定义模型名称,因为该指令可以在同一页面上多次使用。请尝试提供更新
  • 我已经更新了 plnkr,以便您可以将 ng-model 添加到指令中。您传递的变量现在将以两种方式与输入绑定,如演示中所示。更改包括将“ng-model”添加到 script.js 和 index.html。还对模板 html 文件进行了更改,从 'selected' 更改为 'ngModel'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2023-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多