传递AngularJS指令的参数不起作用

时间:2014-02-24 11:29:27

标签: angularjs angularjs-directive

我正在尝试编写我的第一个AngularJS指令。该指令应该扩展DIV元素以包括图片和参数(缩略图)。如果thumbnail == true,则应调整图像大小。我设法显示图片,但没有调整大小。

<!DOCTYPE html>
<html ng-app="ExampleDirective">
<head>
<script type="text/javascript"     src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<script>
 angular.module('ExampleDirective', [])
.controller('MyController', function($scope, $window) {

})
.directive('mypicture', function () {
return {
  restrict: 'A',
  template: '<img src="picture.gif" width="calc()" />',
  scope: {      
    thumbnail: '=',
    },
  link: function (scope, elem, attrs) {

    scope.calc = function() {
      if (scope.thumbnail === 'true') {
        return 50;
      }
    };


  }
}
});

</script>


</head>
<body ng-controller="MyController">

  <div mypicture thumbnail="true" ></div>

</body>
</html>

知道怎么解决吗?
谢谢!

1 个答案:

答案 0 :(得分:1)

尝试改为使用ng-style

<强> JS

app.directive('mypicture', function () {
return {
  restrict: 'A',
  template: '<img src="http://pagead2.googlesyndication.com/simgad/8173680700251715003" 
             ng-style="calc()" />',
  scope: {      
    thumbnail: '=',
    },
  link: function (scope, elem, attrs) {

    scope.calc = function() {       
      if (scope.thumbnail == true) {
          return {width: 150 + 'px'};
      }        
        return {width: 100 + 'px'}
    };
  }
}
});

演示 Fiddle