user2824073
user2824073

Reputation: 2485

Passing arguments to AngularJS directive not working

I'm trying to code my first AngularJS directive. This directive should extend the DIV element to include a picture and a parameter (thumbnail). If thumbnail == true, the image should be resized. I managed to display the picture, yet it is not resized.

<!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>

Any idea how to fix it ?
Thanks!

Upvotes: 0

Views: 88

Answers (1)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Try to use ng-style instead:

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'}
    };
  }
}
});

Demo Fiddle

Upvotes: 1

Related Questions