AngularJS extend Controller within controller

414 views Asked by At

here's my issue: I want to run the code of controllerB into controllerA. The issue is that while the variables are returned to the controllerA, the values from requests are never returned. Here's a plunker to show the issue: http://plnkr.co/edit/GqC9BOKTi8HxQLf2a2yd?p=preview

var test = $scope.$new();
$controller('Ctrl1', {$scope : test});

//the first 2 lines are executed, but the 3d never returns a value
$scope.variable = test.variable;
$scope.varFromFunction = test.varFromFunction();
$scope.varFromRequest = test.varFromRequest;

The first 2 lines execute, but the 3d one never returns a value.

2

There are 2 answers

0
Samir Das On

Since varFromRequest is located inside a $timeout method in the first controller with 500ms, it will execute 500s later meanwhile angular completes its linking phase.

Watching varFromRequest in the second controller is the easy solution

 test.$watch('varFromRequest', function(new_value, old){
  $scope.varFromRequest = test.varFromRequest;

})

Here is the updated plunker http://plnkr.co/edit/TqSjeckrdqeKquEbCwFX

0
skubski On

The varFromFunction is undefined when the second controller tries to get a reference. The timeout sets this var after this request. If you delay the request for reference then you will get the appropriate value. This isn't the recommended way of working but it does answer your question why it hasn't been set yet.

myApp.controller('Ctrl1', ['$scope', '$timeout', function($scope, $timeout) {
    $scope.variable = 'OH HAI';
    $scope.varFromFunction = function(){
      return "OH HAI FromFunction";
    }
    $timeout(function(){
      $scope.varFromRequest = "time";
    },500);

}]);

myApp.controller('Ctrl2', ['$scope', '$controller', '$timeout', function($scope, $controller, $timeout) {
    var test = $scope.$new();
    $controller('Ctrl1', {$scope : test});

    $scope.variable = test.variable;
    $scope.varFromFunction = test.varFromFunction();
    $scope.varFromRequest = test.varFromRequest || 'unset';

    $timeout(function(){
      $scope.varFromRequest = test.varFromRequest || 'still unset';
    },500);
}]);