Mohamed Nagy
Mohamed Nagy

Reputation: 1058

AngularJS cann't access ng-click from ng-view

I'm using angularJS1.2 routing feature to partialy load some views.

var app = angular.module('app', ['ngAnimate', 'ngRoute']).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
        $routeProvider.when('/profile/personalInfo', {templateUrl: '<?php echo base_url().'profile/personalInfo' ?>', controller: personalInfo});
        $routeProvider.when('/profile/myPlaces', {templateUrl: '<?php echo base_url().'profile/myPlaces' ?>', controller: myPlaces});
        $routeProvider.otherwise({redirectTo: '/profile/personalInfo'});
        $locationProvider.html5Mode(true);
    }]);

 function personalInfo($scope, $http){
      console.log('personal info');
  }

  function myPlaces($scope, $http){
      console.log('my places');
      $scope.places = [];
      //then fill places via $http.post request
      $scope.loadMore = function(){
         console.log('clicked');
      }
  }

this is my parial page:

<div>
    <h1>My Places Page</h1>
    <div ng-repeat="place in places">
        <a href="" ng-click="loadMore()">load more</a>
    </div>
</div>

The routing had been done successfully, but when i click the link to call loadMore, then this error appear in the console undefined is not a function. What is the problem and how i can fix it ?

Upvotes: 0

Views: 815

Answers (2)

Wottensprels
Wottensprels

Reputation: 3327

Make it a controller:

app.controller('MyCtrl',function myPlaces($scope, $http){
  console.log('my places');
  $scope.places = [];
  //then fill places via $http.post request
  $scope.loadMore = function(){
     console.log('clicked');
  }
 });

Upvotes: 0

Mohamed Nagy
Mohamed Nagy

Reputation: 1058

I found a soluation, but i'm not sure if this soluation is the optimal but at least it solved the problem. I created a custom directive as the following

app.directive('whenClicked', function() {
        return function(scope, elm, attr) {
            var raw = elm[0];
            angular.element(raw).bind('click', function() {
                console.log('clicked');
            });
        };
    });

and then from the partial page you can call the directive

<div>
    <h1>My Places Page</h1>
    <div ng-repeat="place in places">
        <a href="" when-clicked>load more</a>
    </div>
</div>

Upvotes: 1

Related Questions