0

In this example I'm trying to dynamically set the limit a given array can display.

app-view.html

<things data="things.data" settings="things.settings"></things>

app-controller.js

$scope.$on('thingsCallback', function(e,d){
    $scope.things = d;                
});

Here you will notice limit has not yet been set.

things.html

<ul>
    <li ng-repeat="thing in data | limitTo: limit">
        {{thing.name}}
        <span ng-show="$index==settings.limit-1">
            <show-more min="settings.limit" max="data.length"></show-more>
        </span>
    </li>
</ul>

showMore.html

<li>
    <a href="#" ng-click="toggle()">{{text}}</a>
</li>

Instead I'm using a $watch to wait for the async data to come in. So far so good.

things-directive.js

.directive('things', function() {
    return {
        scope : {
          data : "=",
          settings : "="
        },
        restrict: 'E',
        replace: true,
        controller: function($scope){
          $scope.$watch('settings',function(){
            if($scope.settings){
              $scope.limit = $scope.settings.limit;
            }
          });
        },
        templateUrl: 'things.html'
    };
})

Problems begin:

  • When a user invokes toggle() to "show more", I'm trying to update the value of limit to the max value of data.length which is bound to max.

  • When a user invokes toggle() to "show less", I'm trying to update the value of limit to the min value of settings.length which is bound to min.

show-more-directive.js

.directive('showMore', function() {
    return {
        scope : {
          min : "=",
          max : "="
        },
        restrict: 'E',
        replace: true,
        controller: function($scope){

          $scope.text = 'show more';

          $scope.toggle = function(){
            $scope.text = ($scope.max==$scope.$parent.limit)?'show more':'show less';                
            $scope.$parent.limit = ($scope.min==$scope.$parent.limit)?$scope.max:$scope.min;

            //Shows the value has updated, but the ng-repeat does not update?
            console.log($scope.$parent.limit);
          }
        },
        templateUrl: 'showMore.html'
    };
})

The $scope.$parent.limit seems to change but the the ng-repeat does not update to show the remaining results.

  • How do I change the isolate parent scope through a nested directive?

  • Is there a better way to do this?

4

1 回答 1

0

您可以尝试在 toggle() 的末尾重新编译元素:

.directive('showMore', function ($compile) {
  return {
    ...
    controller: function ($scope, $element) {

      $scope.toggle = function () {
        ...
        $compile($element.contents())($scope);
      }
    },
    ...
  }
于 2013-09-23T20:33:15.127 回答