user3561092
user3561092

Reputation: 47

can't acces method of parent controller from child controller

My html

<section class="localsContainer" ng-controller="LocalsCtrl">
    <h3>Lokale</h3>
    <div class="placesProgress"></div>
    <ul>
        <li ng-repeat="city in cities">
            <p ng-show="city.LocalCount > 0" ng-click="getLocals(city.Id)">{{city.Name}}</p>
            <ul ng-show="activeCityLeft === city.Id">
                <li ng-repeat="local in locals[city.Id]">
                    <p>{{local.Name}} ng-click="getDetails()"</p>   
                </li>
            </ul>
        </li>
        <li ng-if="cities.length == 0">
            <strong>Nie znaleziono</strong>
        </li>
    </ul>
</section>

and js

angular.module('sandboxApp')
  .controller('MainCtrl', function ($scope, API) {
      API.newRequest('getCitiesList').success(function (data, status, headers, config) {
          $scope.cities = data.data;
      });
      $scope.getDetails = function () {
          console.log("test")
      };
  })
  .controller('LocalsCtrl', function ($scope, API) {
      $scope.locals = {};

      $scope.getLocals = function (cityid) {
          $scope.activeCityLeft = cityid;
          API.newRequest('getLocalList', { params: { 'city_id': cityid.toString() }, cache: true }).success(function (data, status, headers, config) {
              $scope.locals[cityid] = data.data;
          });
      };
  })

If i understand correctly i should be able to invoke 'getDetails' method anywhere because it is defined on main controller, even from elements which got their won controllers but are nested within element attached to main controller. but it does'nt work, when i click on element which should invoke getDetails, instead it displays 'ng-click="getDetails()' as html text.

Upvotes: 0

Views: 45

Answers (2)

A.B
A.B

Reputation: 20445

use ng-click as attribute since it is directive and directives(attribute) are used like attributes, you are displaying it as text

see refrence for ng-click

 <p ng-click="getDetails()">{{local.Name}} </p>  

Upvotes: 2

Omri Aharon
Omri Aharon

Reputation: 17064

Your ng-click is defined wrong - you defined it as text inside a <p> element:

<p>{{local.Name}} ng-click="getDetails()"</p>

You should define it as an attribute since it is a directive:

<p ng-click="getDetails()">{{local.Name}}</p> 

Upvotes: 2

Related Questions