Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. <my-directive data-allow-something="false">
  2. ... this works as expected as no default value should be set in this case ...
  3. </my-directive>
  4.  
  5. <my-directive>
  6. ... but in this case i'd like allowSomething to equal true ...
  7. </my-directive>
  8.  
  9. angular.module('myApp').directive('myDirective') {
  10. ...
  11. controller: function($scope){
  12. if (!$scope.allowSomething)
  13. $scope.allowSomething = true;
  14. },
  15. ....
  16. scope: function(){
  17. allowSomething: '@'
  18. }
  19. ...
  20. }
  21.  
  22. controller: function($scope){
  23. if (angular.isUndefined($scope.allowSomething))
  24. $scope.allowSomething = true;
  25. }
  26.  
  27. <my-directive allow-something="false"></my-directive>
  28. <my-directive></my-directive>
  29.  
  30. angular
  31. .module('app')
  32. .directive('myDirective', function() {
  33.  
  34. var defaults = {
  35. allowSomething: true
  36. };
  37.  
  38. return {
  39. restrict: 'E',
  40. templateUrl: '',
  41. scope: {},
  42. compile: function() {
  43. return {
  44. pre: function(scope, el, attrs) {
  45. scope.allowSomething = attrs.allowSomething || defaults.allowSomething;
  46. },
  47.  
  48. post: function(scope, el) {
  49. // this is link
  50. // scope.allowSomething = default or whatever you enter as the attribute "false"
  51. }
  52. };
  53. }
  54. };
  55. }
  56.  
  57. scope : true,
  58. link : function(scope, element, attrs){
  59. scope.allowSomething = $parse(attrs.allowSomething)(scope) || true;
  60. console.log(scope)
  61. }
  62.  
  63. <body>
  64. <my-directive></my-directive>
  65. <!-- <my-directive allow-something="false"></my-directive> -->
  66. </body>
  67.  
  68. angular.module('myApp', [])
  69. .directive('myDirective', function() {
  70. return {
  71. scope: {},
  72. link: function(scope, element, attrs) {
  73. scope.allowSomething = ('allowSomething' in attrs) ? attrs.allowSomething : true;
  74. },
  75. template: '<div>allow:{{ allowSomething }}</div>'
  76. };
  77. });
  78.  
  79. angular.module('myApp', [])
  80. .directive('myDirective', function() {
  81. return {
  82. scope: {
  83. allowSomething: '@'
  84. },
  85. controller: function($scope, $timeout) {
  86. $timeout(function() {
  87. if (angular.isUndefined($scope.allowSomething)) {
  88. $scope.allowSomething = true;
  89. }
  90. });
  91. },
  92. template: '<div>allow:{{ allowSomething }}</div>'
  93. };
  94. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement