2016-06-17 2 views
1

의 모든 컨트롤러 의존성 해결 : I가 다른 제어기 (하위 제어기)를 사용하여 템플릿 HTML에서를 주입은이 같은 UI 라우터 상태를 UI 라우터

$stateProvider.state('parent', { 
    templateUrl: 'tpl/a.html', 
    resolve: { 
    resA: function() { 
     return { 'value': 'A' }; 
    } 
    }, 
    controller: function($scope, resA) { 
    $scope.resA = resA.value; 
    } 
}); 

한다. 이 하위 컨트롤러는 ui 라우터 상태의 종속성을 해결해야합니다. 그러나 자식 컨트롤러에는 주입되지 않습니다.

TPL/a.html

<h1>Hello</h1> 
<div ng-controller="ChildCtrl"> 
</div> 

ChildCtrl

var app = angular.module('app', []); 
app.controller('ChildCtrl', function($scope, resA) { 
    // some codes 
}); 

나는 ChildCtrl에, 그 RESA의 unkonwn을 오류를 얻었다. ChildCtrl에 resA를 삽입하는 방법?

//it would be available in child controller in `$scope.a` 
$stateProvider.state('parent', { 
    templateUrl: 'tpl/a.html', 
    resolve: { 
    resA: function() { 
     return { 'value': 'A' }; 
    } 
    }, 
    controller: function($scope, resA) { 
    $scope.resA = resA.value; 
    } 
}) 
.state('parent.child', { 
    templateUrl: 'tpl/child.html', 
    controller: function($scope) { 
    console.log($scope.resA) //'{value: "A"}' 
    } 
}); 

2) 하위 경로에 대한 컨트롤러로 아이 컨트롤러를 넣어

1) 부모 컨트롤러의 $ 범위의 값을 넣어뿐만 아니라이 RESA를 해결 :

답변

2

나는 3 옵션을 참조하십시오

var a = { 'value': 'A' }; 
$stateProvider.state('parent', { 
    templateUrl: 'tpl/a.html', 
    resolve: { 
    resA: function() { 
     return a; 
    } 
    }, 
    controller: function($scope, resA) { 
    $scope.resA = resA.value; 
    } 
}) 
.state('parent.child', { 
    templateUrl: 'tpl/child.html', 
    resolve: { 
    resA: function() { 
     return a; 
    } 
    }, 
    controller: function($scope, resA) { 
    $scope.resA = resA.value; 
    } 
}); 

3) 컨트롤러 (지금 RESA에 저장되는) 데이터를 제공하는 몇 가지 서비스를하고 두 제어기에 주입

,
+0

답변 해 주셔서 감사합니다. 나는 2 단계에서 이해하지 못한다. 몇 가지 코드를 추가 할 수 있습니까? – windupurnomo

+0

@windupurnomo, 답을 확인, 예를 넣었습니다 – BotanMan

0

Checkout @ BotanMan의 답변입니다.

또 다른 방법은 3. 답과 비슷합니다.

리소스를 서비스에 포함하십시오.

var app = angular.module('app'); 
app.service('resA', function() { 
    // your service here 
}); 

그리고 지금처럼이 포함됩니다 의도처럼

$stateProvider.state('parent', { 
    templateUrl: 'tpl/a.html', 
    resolve: { 
    resA: 'resA' //your service name 
    }, 
    controller: function($scope, resA) { 
    $scope.resA = resA.value; 
    } 
}); 

그래서 당신은 그 자원을 사용할 수 있습니다

var app = angular.module('app', []); 
app.controller('ChildCtrl', function($scope, resA) { //now it should work 
    // some codes 
}); 

이 결의에 docs를 참조하십시오.

+0

답장을 보내 주셔서 감사합니다 @eenagy. 내 ChildCtrl 너무 다른 상태에서 사용됩니다. 그것은 의존성 해결과 서비스로서의 작업입니까? 내 질문을 업데이트합니다 ... – windupurnomo