2014-06-30 53 views
0

我已經構建了一個指令,將$ rootScope.showContent值更改爲true或false。切換元素可見性的角度指令

然後,我使用ng-show =「showContent」來隱藏或顯示元素。

這種方法工作正常,但我想避免使用$ rootScope,也使用scope.apply()函數。 你能否建議我一個更好的方法來做到這一點?

下面你會發現一些代碼:

HTML

<body ng-app="myApp"> 
    <div ng-controller="AppCtr"> 
     <hide-amounts ></hide-amounts> 

     <div ng-show="showContent"> 
      <h1>Hello from h1</h1> 
      <p>Hello from paragarapsh</p> 
     </div> 
     <div ng-show="showContent"> 
      <h1>Hello from h1</h1> 
      <p>Hello from paragarapsh</p> 
     </div> 
    </div> 
</body> 

var myApp = angular.module('myApp', []); 

myApp.run(function ($rootScope) { 
    $rootScope.showContent = true; 
}) 

myApp.controller("AppCtr", function ($scope) { 

}) 
.directive('hideAmounts',["$rootScope", function ($rootScope) { 
    return { 
     restrict: "E", 
     replace: true, 
     template: '<a href="#">Hide Content</a>', 
     link: function (scope, element, attrs) { 
      element.click(function() { 
       scope.$apply(function() { 
        $rootScope.showContent = !$rootScope.showContent; 
       }) 
       return false; 
      }) 
     } 
    }; 
}]); 

的jsfiddle鏈接:http://jsfiddle.net/RickyStam/AkVzz/(沒有的jsfiddle工作不知道爲什麼: P)

回答

1

說實話它不是好主意,定義指令只是切換標誌父控制器上

只使用

<button ng-click="showContent = !showContent "> 

代替。

但是,如果你真的想擺脫OG $ rootScope您可以:

1)傳遞參數,以指令jsfiddle

<hide-amounts show="showAmounts" ></hide-amounts> 

var myApp = angular.module('myApp', []); 

myApp.controller("AppCtr", function ($scope) { 
    $scope.obj = {}; 
    $scope.obj.showAmounts = true; 
    $scope.showAmounts = true; 
}) 
.directive('hideAmounts',["$rootScope", function ($rootScope) { 
    return { 
     restrict: "E", 
     replace: true, 
     scope: {show:'='}, 
     template: '<a href="#">Hide Amounts</a>', 
     link: function (scope, element, attrs) { 
      element.click(function() { 
       scope.$apply(function() { 
        scope.show = !scope.show; 
       }) 
       return false; 
      }) 
     } 
    }; 
}]); 

2)通過調用$ scope.emit發送消息給父控制器('message',param)並在父控制器上註冊監聽器$ scope.on('message,function(s,param){})

+0

感謝您的幫助!非常感激 :) –

0

避免使用獨立的scope指令,除非需要。而且你知道在AngularJS 1.2.x之前,孤立的範圍和正常的指令沒有太大的區別。但在1.2.x版本中,他們改變了他們的行爲。所以,我不得不改變我的項目中的所有指令。所以,請確保,除非需要,否則請使用。

var myApp = angular.module('myApp', []); 
myApp.controller("AppCtr", function ($scope){ 
    $scope.obj = {}; 
    $scope.obj.showAmounts = true; 
    $scope.showAmounts = true; 
}) 

.directive('hideAmounts', ["$rootScope", function ($rootScope) { 

    return { 
     restrict: "E", 
     replace: true, 
     template: '<a href="#">Hide Amounts</a>', 
     link: function (scope, element, attrs) { 
      element.click(function() { 
       scope.showAmounts = !scope.showAmounts; 
       scope.$apply(); 
      }) 
     } 
    }; 
}]); 

而其他的事情是你可以在指令中使用父範圍(直到它不是一個孤立的範圍指令)。