Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting controller name from $parent in AngularJS

I have converted one of my Angular controllers to Controller As syntax, but I am having trouble getting an ng-grid template to play nicely.

The controller has a function called edit user that looks like this

self.editUser = function (user_data) {
    var modalInstance = $modal.open({
        templateUrl: '/admin/views/adminuser.html',
            controller: 'AdminUserController',
            resolve: {
                user_data: function () {
                    return user_data;
                }
            }
        });

        modalInstance.result.then(function () {
            self.myQueryData.refresh = !self.myQueryData.refresh;
        });
    };

the ng-grid template looks like this

<div class="ngCellText" ng-class="col.colIndex()">
    <a ng-click="$parent.$parent.$parent.$parent.editUser({user_id:row.entity.id, first_name:row.entity.first_name, last_name:row.entity.last_name, email:row.entity.email})">
        <span ng-cell-text translate>Edit</span>
    </a>
</div>

and my route looks like this

.when('/admin/settings', {
    templateUrl: '/admin/views/settings.html',
    controller: 'SettingsController as sc',
})

So the problem is in the template when I call

$parent.$parent.$parent.$parent.editUser 

it doesn't know what I am talking about unless I include the controller name like

$parent.$parent.$parent.$parent.sc.editUser, 

then it works great. However I don't want to bind this template directly to the sc controller. How can I call the editUser without using the controller name?

I was hoping there would be a function on the $parent that would supply the function name like

$parent.$parent.$parent.$parent.getController().editUser

Any suggestions?

like image 384
ryanmc Avatar asked Nov 10 '22 02:11

ryanmc


1 Answers

You can call functions on parent scope directly without referring to $parent. Because you might get in to trouble later when you modify your view structure.

example:

<div ng-app="MyApp">
<div ng-controller="MyController">
    {{myMessage}}
    <div ng-controller="MyController2">
        <div ng-controller="MyController3">
            <div ng-controller="MyController4">
                <button id="myButton" ng-click="setMessage('second')">Press</button>
            </div>
        </div>
    </div>
    <script>
        angular.module('MyApp', [])
           .controller('MyController', function($scope) {
            $scope.myMessage = "First";
               $scope.setMessage = function(msg) {
                $scope.myMessage = msg;
               };
        }).controller('MyController2', function($scope) {

           }).controller('MyController3', function($scope) {

           }).controller('MyController4', function($scope) {

           });
    </script>

</div>
</div>

Or else you can use angular $broadcast

like image 115
Ravi Dasari Avatar answered Nov 14 '22 21:11

Ravi Dasari