简体   繁体   English

如何在我的指令中连接控制器以在angular.js中插入数据和添加引导选择?

[英]How to connect my controller in my directive for inserting data and adding bootstrap select in angular.js?

I'm trying to add data on my select menu using a controller and used ng-options while i have a class defined in my directive to insert the bootstrap-select plugin to the element. 我正在尝试使用控制器在SELECT菜单上添加数据,并使用ng-options,同时我在指令中定义了一个类来将bootstrap-select插件插入到元素中。 The problem is that the data in my controller didn't work, it's having conflict on my directive and i even tried using require and controller method in my directive. 问题是控制器中的数据不起作用,指令上存在冲突,甚至尝试在指令中使用require和controller方法。

Please take a look at my code: 请看一下我的代码:

HTML HTML

<div ng-controller="CitiesController" class="form-group pull-left form-register-width-field form-register-select">
   <label for="city">City</label>
   <select id="city" ng-model="selectedItem" ng-options="item as item.name for item in cities" class="selectpicker">
     <option>Select City</option>
  </select>
</div>  

My controller: 我的控制器:

function CitiesController($scope) {
  console.log('cities controller'); 
  $scope.cities = [
    {value:'1',name:'Angeles'},
    {value:'2',name:'Angono'},
    {value:'3',name:'Antipolo'},
    {value:'4',name:'Apalit'},
    {value:'5',name:'Arayat'},
    {value:'6',name:'Bacolod'},
    {value:'7',name:'Bacoor'}
   ];
  console.log($scope.cities[2]);
 }

My directive: 我的指令:

angular.module('myApp.directives', [])
.directive('selectpicker', function() {
   return {
     restrict: 'C',
     link: function(scope,el,attr,cntr) {
       $(el).selectpicker();
     }
   }
})

Thanks for the help :) 谢谢您的帮助 :)

Try adding controller in your directive itself like ths; 尝试在指令本身中添加控制器,例如:

angular.module('myApp.directives', [])
.directive('selectpicker', function() {
   return {
     restrict: 'C',
     controller: function($scope){
       $scope.cities = [
         {value:'1',name:'Angeles'},
         {value:'2',name:'Angono'},
         {value:'3',name:'Antipolo'},
         {value:'4',name:'Apalit'},
         {value:'5',name:'Arayat'},
         {value:'6',name:'Bacolod'},
         {value:'7',name:'Bacoor'}
       ];
     },
     link: function(scope,el,attr,cntr) {
       $(el).selectpicker();
     }
   }
});

Angular strap provide directive for the same "bsSelect" below is the url: 角带提供以下URL的同一“ bsSelect”指令:

http://mgcrea.github.io/angular-strap/#/select http://mgcrea.github.io/angular-strap/#/select

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM