簡體   English   中英

從具有隔離范圍的角度指令獲取變量

[英]Get variable from angular directive with isolated scope

我正在使用angular@1.6.3bootstrap@3.3.7 jquery@1.12.4jquery@1.12.4

我正在嘗試將<select>標簽包裝到bootstrap-multiselect jQuery插件中。

為此,我嘗試將自定義指令與孤立的范圍一起使用。

這是我的HTML:

<div ng-app="myApp" ng-controller="MainCtrl as vc">
  <select multiple="multiple"
          multiselect
          ng-model="vc.selectedCountries"
          data-options="vc.allCountries"
          data-list-type="Countries">
      <optgroup ng-repeat="(continent, countries) in options" label="{{continent}}">
        <option ng-repeat="country in countries" value="{{country.code}}">
        {{country.code}} - {{country.name}}
        </option>
      </optgroup>
  </multiselect>
</div>

這是我的JS:

var app = angular.module('myApp', [])

app.controller('MainCtrl', ['$scope', '$http', function ($scope, $http) {
  var self = this

  self.allCountries = {}

  $http.get('/countries.json')
    .then(function (result) {
      self.allCountries = result.data
    })
}])

app.directive('multiselect', [function () {
  return {
    restrict: 'A',
    scope: {
      options: '=',
      listType: '@',
    },
    transclude: true,
    controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
      $scope.$watch('options', function(newVal, oldVal) {
        console.log(newVal, oldVal)
        $timeout(function () {
          console.log($scope.options)
          $($element).multiselect('rebuild')
        }, 1)
      })

      $($element).multiselect()
    }]
  }
}])

但是,這樣就不會填充<select> 插件本身不是問題,因為如果我刪除包含.multiselect()調用的行,則常規multiselect會顯示為空。

我認為這與包含和范圍有關,因為如果我將transclude: true,更改為transclude: false,

<optgroup ng-repeat="(continent, countries) in options" label="{{continent}}">

<optgroup ng-repeat="(continent, countries) in vc.allCountries" label="{{continent}}">

它工作正常。

但是,我試圖概括該組件,所以我不想依賴於控制器。

您不必依賴您在代碼中編寫的控制器。 您可以嘗試這種替代方法。

<!DOCTYPE html>
<html ng-app="exampleApp" >
    <head>
        <meta charset="utf-8">
        <title>ng app</title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js" type="text/javascript"></script>
        <script>
            var myApp = angular.module('exampleApp', []);
            myApp.directive('highlight', function(){
                return function (scope, element, attrs) {
                    console.log(scope.$root.list);
                }
            });

        myApp.run(function($rootScope){
           $rootScope.list = [1,2,3];
        });
        </script>
    </head>
    <body>
        <highlight listdata="$parent.list"></highlight>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM