2017-02-24 34 views
0

嗨我試圖控制基於內部指令的值的HTML。在我的情況下如何從指令發送數據到父控制器?

我有這樣的HTML:

//myCtrl.isLoad was set to false 
<img ng-src="{{myCtrl.url}}" imageonload></img> 
<div ng-if="myCtrl.isLoad">Show me</div> 

指令:

angular.module('myApp') 
     .directive('imageonload', imageonloadFunction); 

    function imageonloadFunction() { 
     var directive = { 
      'link': link,     
      'restrict': 'A' 
     }; 

     return directive; 
    } 

    function link($scope, element, attrs) { 
     some other codes..   
     //Do something if the condition is met 
     //and change myCtrl.isLoad = true so 
     //<div ng-if="myCtrl.isLoad">Show me</div> 
     //will show 
    } 

我不知道的最好方式指令數據綁定到父。任何人都可以幫助我嗎?非常感謝!

+0

你必須到'myCtrl.isLoad'變量傳遞給指令...'

Show me
' –

回答

1

您可以將控制器屬性綁定到指令。

angular.module('myApp', []) 
 
     .directive('imageonload', imageonloadFunction); 
 

 
    function imageonloadFunction() { 
 
     var directive = { 
 
      'link': link, 
 
      'scope': { 
 
       'isLoad': '=' 
 
      }, 
 
      'restrict': 'A' 
 
     }; 
 

 
     return directive; 
 
    } 
 

 
    function link($scope, element, attrs) { 
 
     $scope.isLoad = true; 
 
     //Do something if the condition is met 
 
     //and change myCtrl.isLoad = true so 
 
     //<div ng-if="myCtrl.isLoad">Show me</div> 
 
     //will show 
 
    }
//myCtrl.isLoad was set to false 
 
<img ng-src="{{myCtrl.url}}" imageonload is-load="myCtrl.isLoad"></img> 
 
<div ng-if="myCtrl.isLoad">Show me</div>

0

顯示裝載機當圖像負載。

在HTML:

<img src="img/loading.gif" imageload="{{myCtrl.url}}"> 

指令:

.directive('imageload', function() { 
     return { 
      restrict: 'A', 
      scope: { 
       imageload: '@' 
      }, 
      link: function(scope, element, attrs) { 
       element.one('load', function() { 
        element.attr('src', scope.imageload); 

       }); 
      } 
     }; 
    }) 
相關問題