2014-02-24 68 views
0

我試圖編寫我的第一個AngularJS指令。該指令應擴展DIV元素以包含圖片和參數(縮略圖)。如果thumbnail == true,則圖像應該調整大小。我設法顯示圖片,但沒有調整大小。將參數傳遞給AngularJS指令不起作用

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

嘗試使用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

+0

謝謝!有用! – user2824073

相關問題