AngularJS在控制器内扩展控制器

时间:2015-06-19 08:08:03

标签: angularjs controller extend

这是我的问题:我想将controllerB的代码运行到controllerA中。问题是,当变量返回到controllerA时,永远不会返回来自请求的值。这是一个显示问题的傻瓜: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;

前两行执行,但3d一行永远不会返回值。

2 个答案:

答案 0 :(得分:0)

由于XMLSlideShow ppt = new XMLSlideShow(); XSLFSlide slide = ppt.createSlide(); XSLFTextBox shape = slide.createTextBox(); XSLFTextParagraph p = shape.addNewTextParagraph(); XSLFTextRun r1 = p.addNewTextRun(); r1.setText("the"); r1.setFontColor(Color.blue); r1.setFontSize(24); OutputStream out = new FileOutputStream("d:/font.pptx"); ppt.write(out); out.close(); 位于第一个控制器的$ timeout方法内500ms,它将在500s后执行,同时angular完成其链接阶段。

在第二个控制器中观察varFromRequest是一个简单的解决方案

varFromRequest

这是更新的plunker http://plnkr.co/edit/TqSjeckrdqeKquEbCwFX

答案 1 :(得分:0)

当第二个控制器尝试获取引用时,varFromFunction未定义。超时在此请求后设置此var。如果您延迟参考请求,那么您将获得适当的值。这不是推荐的工作方式,但它确实回答了您为什么尚未设置的问题。

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);
}]);