Nere
Nere

Reputation: 4097

Unable to call $scope function in ng-repeat

I have this function showPopupSelectTopic(subject) to call in my ng-repeat html code. But it does not work at all.

         <div style="width:100%;" ng-controller="manageStudyCtrl">
            <div class="div-subject" ng-repeat="subject in dataSubject" ng-click="showPopupSelectTopic(subject)">  
                <div class="round-button-subject-2">
                    <div class="subject-name-2 subject-eng" style="color:{{subject.subject_code.colour_code}}">
                        {{subject.subject_code.short_name}}
                        <div>{{subject.avg_overall_coverage | number : 0}}%</div>
                    </div>
                    <circular-progress
                        value = "subject.avg_overall_coverage"
                        max="100"
                        orientation="1"
                        radius="36"
                        stroke="8"
                        base-color="#b9b9b9"
                        progress-color="{{subject.subject_code.colour_code}}"
                        iterations="100"
                        animation="easeInOutCubic"
                    ></circular-progress>
                </div>
            </div>
          </div>

I want to call my showPopupSelectTopic(subject)in my controller so that I can make popup and manipulate the data.

I have done outside from ng-repeatand its working perfectly. However if I used in ng-repeat then it would not execute as expected. How to solve this issue?


My controller:

angular.module('manageStudy', [])
.controller('manageStudyCtrl', function($scope,){

$scope.showPopupSelectTopic = function(subject) {
    alert(subject.chapter_id);
};
});

Upvotes: 0

Views: 256

Answers (2)

Aer0
Aer0

Reputation: 3907

That's not possible due to every ng-repeat creating its own child scope. That being said, ever functio invocation will lead the child to copy some variables into its own scope. You'd have to use their parentscope or refere to the origin $scope of your controller.

ng-click="$parent.showPopupSelectTopic(subject)"

This should solve the problem. However, it's kinda dirty. A better solution would be to return your parents scope and use it in every child scope just like that. So declare a function inside of your controller (e.g. $scope.getScope) and let it simply return its $scope. Afterwards you'll be able to access it properly.

$scope.getScope = function() {
  return $scope;
}

ng-click = "getScope().showPopupSelectTopic(subject)"

Upvotes: 1

Osama Salama
Osama Salama

Reputation: 647

ng-repeat works only with an iterate able object, like array or collection. Before you open the div where you intent to repeat, the iterate able object must be in ready in the scope. Try using ngInit instead of ngClick to initialize the array before attempting to ngRepeat

Upvotes: 0

Related Questions