0

first I will show you my html:

  <div class="pager" pager-control getPageNumber="getPageNumber()" getPageData="getPageData()">

my purpose of this "directive" is making pager. and this is the js file blew:

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

paging.controller('pageCtrl',function($scope,$timeout){


$scope.currentPageIndex = 0;
$scope.model = [
  { name: 'www'},
  { name: 'www'},
  { name: 'www'},
  { name: 'www'},
  { name: 'www'}
];

$scope.getPageNumber = function(){
  var len = 10,ret=[];
  for(i = 0;i < 10; i++) {
    ret.push(i);
  }
  return ret;
};

$scope.getPageData = function(index) {
  $scope.currentPageIndex = index;
  alert('trigger!');
};
});

paging.directive('pagerControl',function(){

 return {
  restict: 'A',
  replace: false,
  transclude: true,
template: '<ul ng-transclude><li ng-class="{current: $parent.currentPageIndex == $index}" ng-repeat="d in $parent.getPageNumber()" ng-click="$parent.getPageData($index)">{{$index + 1}}</li>    </ul>',
scope: {

},

link: function(scope,elem,attr) {

}

};

});

expect to "when you click the page item,the color will change ",but nothing happends..

this is the jsbin url:
http://jsbin.com/vijax/2/edit

Daniel.Woo
  • 636
  • 1
  • 10
  • 17

1 Answers1

0

I fixed your jsbin:

http://jsbin.com/kaziqice/2/edit

There are 2 issues with your code:

1) ng-repeat creates child scopes.

You have to replace ng-click="$parent.getPageData($index)" with ng-click="$parent.$parent.getPageData($index)" to access the correct scope

2) Replace currentIndex="currentPageIndex" with current-index="currentPageIndex". This is the naming convention of angular Angular JS naming conventions ($, camelCase and PascalCase)

For the first problem, you should not bind directly to your parent scope as it will create a tight coupling in code. You should bind to your scope's own properties instead.

Community
  • 1
  • 1
Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • Thank you it works ..but why "$parent.$parent.getPageData($index)" not "$parent.getPageData($index)"? thx again – Daniel.Woo Feb 27 '14 at 13:34
  • @Daniel.Woo: because `ng-repeat` creates child scope => there is `1 more level` deep. $parent is your directive's scope and $parent.$parent is your controller's scope. – Khanh TO Feb 27 '14 at 13:36