简体   繁体   English

角-没有$ scope的指令中的引用范围变量?

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

I'm trying to display the first image in an array that is fed into my directive, however, I do not understand why this doesn't work. 我正在尝试在输入到指令中的数组中显示第一个图像,但是,我不明白为什么这不起作用。 Can you please explain? 你能解释一下吗?

Script.js file: 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: HTML:

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

You just need to correct your template to: 您只需要将模板更正为:

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

You're missing the quotes " " around the ng-src attribute, and you can just access the directive's isolate $scope directly with images[0] . 您在ng-src属性中缺少引号" " ,并且可以直接使用images[0]直接访问指令的isolate $ scope。 Your img tag is also missing the closing bracket > . 您的img标签也缺少右括号>

This is how you can access images within the vm controller: 这是您可以在vm控制器中访问images的方式:

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

You can use bindToController to automatically bind the directive's isolate scope to the controller. 您可以使用bindToController自动将指令的隔离范围绑定到控制器。 Just make sure you do have the controller property present or it will throw an error. 只要确保您确实具有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