Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method overloading \ overriding in AngularJS

I have a scenario, i which I have a share button, I have a container controller, called metaCtrl, which is on the html tag.

And also inner controllers.

I have a share button, that calls the model.share() function on click.

code:

app.controller('metaCtrl', function($scope){
$scope.model = {};
    $scope.model.share = function(){
        $location.path('/share').search({'share' : '1'});
    }
});

The controller of the share page it self:

app.controller('shareCtrl', function($scope)){
 $scope.layout.shareVisible = $location.path().share == 1 ? true : false;
    $scope.model.share = function(){
         $scope.layout.shareVisible = $scope.layout.shareVisible ? false : true;
         var shareUrlValue = $scope.layout.shareVisible ? 1 : null;

         $location.search('share', shareUrlValue);
    }
});

The idea is to use the same HTML pattern in the entire application, but only to toggle the share section on the share page(if the user is already there), and to send the user to the share view if he is not currently there.

The problem is that after I go to the sahre page, and then return to the other page, the function share() has a referance to the function in the shareCtrl, rather then to the metaCtrl.

like image 343
Oleg Belousov Avatar asked Nov 02 '22 14:11

Oleg Belousov


1 Answers

I'm not sure there's enough information here, but I'll take a shot at it (I can't comment because I don't have enough rep). Notice that your shareCtrl is not creating a new model object, you're just assigning $scope.model.share = func....

That assignment is overriding the function in the parent controller because Angular is going up the scope chain to find the model object.

See this Plunker: http://plnkr.co/edit/yv5rrpdlkniZdg94T4Lf

Notice with $scope.model = {} commented out in shareCtrl, the value of both fields is "shareCtrl". But, if you uncomment that line, then $scope.model is within the shareCtrl scope so Angular doesn't go up the scope chain looking.

like image 144
Craig Squire Avatar answered Nov 15 '22 13:11

Craig Squire