通过嵌套指令访问隔离父范围

时间:2013-09-23 18:45:48

标签: javascript angularjs

在这个例子中,我试图动态设置给定数组可以显示的limit

应用-view.html

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

应用-controller.js

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

您将注意到limit尚未设置。

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>

相反,我使用$watch等待异步数据进入。到目前为止一直很好。

事情-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'
    };
})

问题开始:

  • 当用户调用toggle()显示更多”时,我正在尝试将limit的值更新为{{1}的最大值绑定到data.length

  • 当用户调用max到“显示更少”时,我正在尝试将toggle()的值更新为最小值{{1绑定到limit

显示-更directive.js

settings.length

min似乎发生了变化,但.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' }; }) 未更新以显示剩余的结果。

  • 如何通过嵌套指令更改隔离父作用域?

  • 有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

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

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

      $scope.toggle = function () {
        ...
        $compile($element.contents())($scope);
      }
    },
    ...
  }
相关问题