castillo-io / angular-css

CSS on-demand for AngularJS [Looking for New Maintainers]
http://castillo-io.github.io/angular-css/#/
MIT License
470 stars 86 forks source link

v1.0.8 two instance of same directives(or controller) in one scene #86

Open soonwait opened 7 years ago

soonwait commented 7 years ago

I had add two directives to one view same time. like this:

<div ui-view>
  <div test-my-directive data-ng-if="model1">DIV 1<div>
  <div test-my-directive data-ng-if="model2">DIV 2<div>
<div>

I used $css.bind(....., $scope) in controller of directive

when i try to close DIV2 by set model2 === false DIV1'css style dispeared unexpectly!!! why ????

soonwait commented 7 years ago

It's a Suggestion as: every call of $css.bind(..., $scope) for same stylesheet url should save all the refrence of $scope while $scope.$on('$destroy' before to $css.remove, shuld check if refrence is 0, only 0 can be remove, otherwise JUST 'remove' the refrence of $scope.

soonwait commented 7 years ago

I have try to fix this


line 459
+      $css.stylesheetRefrences = {};

      /**
       * Bind: binds css in scope with own scope create/destroy events
       **/
       $css.bind = function (css, $scope) {
        if (!css || !$scope) {
            if(DEBUG) $log.error('No scope or stylesheets provided');
            return;
        }
        var result = [];
        // Adds route css rules to array
        if (angular.isArray(css)) {
          angular.forEach(css, function (cssItem) {
            result.push(parse(cssItem));
          });
        } else {
          result.push(parse(css));
        }
+       angular.forEach(result, function(stylesheet){
+         var href = stylesheet.href;
+         if(!$css.stylesheetRefrences[href]) { $css.stylesheetRefrences[href] = [];}
+         var arr = $css.stylesheetRefrences[href];
+         if(arr.indexOf($scope) < 0) {
+           arr.push($scope);
+         }
+       });
        $css.add(result);
        if(DEBUG) $log.debug('$css.bind(): Added', result);
        $scope.$on('$destroy', function () {
-          $css.remove(result);
-          if(DEBUG) $log.debug('$css.bind(): Removed', result);
+         var stylesheets = [];
+         angular.forEach(result, function(stylesheet){
+           var arr = $css.stylesheetRefrences[stylesheet.href], idx = -1;
+           if(arr && (idx = arr.indexOf($scope)) >= 0) {
+             arr.splice(idx, 1);
+           }
+           if(arr.length <= 0) {
+             stylesheets.push(stylesheet);
+           }
+         });
+         if(stylesheets.length > 0) {
+           $css.remove(result);
+           if(DEBUG) $log.debug('$css.bind(): Removed', result);
+         }
        });
       };