簡體   English   中英

角-沒有$ scope的指令中的引用范圍變量?

[英]Angular - Reference scope variable in directive without $scope?

我正在嘗試在輸入到指令中的數組中顯示第一個圖像,但是,我不明白為什么這不起作用。 你能解釋一下嗎?

Script.js文件:

angular.module('app',[])

.controller('MyController', function() {
  var self = this;
  self.imageList=[
    'https://upload.wikimedia.org/wikipedia/commons/3/3d/Polar_Bear_AdF.jpg',
    'http://www.polarbearsinternational.org/sites/default/files/styles/media_full/public/00473-10104_0.jpg?itok=uv9Mr5rz',
    'http://www.polarbearsinternational.org/sites/default/files/styles/inside_full/public/sca-000005.jpg?itok=7HybQm2o'
  ];
})

.directive('myImageGallery', function(){
  return {
    restrict: 'E',
    scope:{
      images: '='
    },
    controller: function() {
    },
    controllerAs: 'vm',
    template: '<ul><img images="vm.images" ng-src={{ vm.images[0] }}</li></ul>'
  }
})

HTML:

<body ng-app="app">
  <div ng-controller="MyController as myCtrl">
    <my-image-gallery images="myCtrl.imageList"></my-image-gallery>
  </div>
</body>

您只需要將模板更正為:

template: '<ul><li><img ng-src="{{images[0]}}"></li></ul>'

您在ng-src屬性中缺少引號" " ,並且可以直接使用images[0]直接訪問指令的isolate $ scope。 您的img標簽也缺少右括號>

這是您可以在vm控制器中訪問images的方式:

scope:{
  images: '='
},
controller: function($scope) {
  this.images = $scope.images;
},
controllerAs: 'vm',
template: '<ul><li><img ng-src="{{vm.images[0]}}"></li></ul>'

您可以使用bindToController自動將指令的隔離范圍綁定到控制器。 只要確保您確實具有controller屬性,否則它將引發錯誤。

.directive('myImageGallery', function(){
  return {
    restrict: 'E',
    scope:{
      images: '='
    },
    controller: function() {},
    controllerAs: 'vm',
    bindToController: true,
    template: '<ul><li><img ng-src="{{vm.images[0]}}"</li></ul>'
  };
});

暫無
暫無

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

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