我正在嘗試編寫一個指令,要求在角度-UI路由器狀態定義中配置的父控制器。爲什麼我的指令不需要由angular-ui-router創建的控制器?
指令「嗶」有需要:「^子控制器
‘子控制器’是用於在角-UI-路由器配置的視圖控制器。
該視圖包含使用指令「beep」的元素。
但是:只要導航到子狀態,就有一個例外說「子控制器無法找到」。
angular-ui-router中的問題?我的一些誤解?
重現:只需點擊「運行代碼片斷」,然後點擊「亞狀態」按鈕:
angular
\t .module('foo', ['ui.router'])
\t .controller('subController', function() {
\t \t console.log("subController");
\t })
\t .config(function ($stateProvider, $urlRouterProvider) {
\t \t $urlRouterProvider.otherwise("/root");
\t \t $stateProvider
\t \t \t .state('root', {
\t \t \t \t url: '/root',
\t \t \t \t views: {
\t \t \t \t \t root: {
\t \t \t \t \t \t template: '<button ui-sref="root">Root State</button>' +
\t \t \t \t \t \t '<button ui-sref="root.sub">Sub State</button>' +
\t \t \t \t \t \t '<div ui-view="sub"></div>'
\t \t \t \t \t }
\t \t \t \t }
\t \t \t })
\t \t \t .state('root.sub', {
\t \t \t \t url: '/sub',
\t \t \t \t views: {
\t \t \t \t \t sub: {
\t \t \t \t \t \t controller: 'subController',
\t \t \t \t \t \t template: '<div beep>SUB</div>'
\t \t \t \t \t }
\t \t \t \t }
\t \t \t });
\t })
\t .directive('beep', function() {
\t \t return {
\t \t \t restrict: 'A',
\t \t \t require: '^subController',
\t \t \t link: function (scope, element, attributes, subController) {
\t \t \t \t console.log("beep: linked", subController);
\t \t \t }
\t \t };
\t })
;
<!DOCTYPE html>
<html lang="en">
\t <head>
\t \t <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
\t \t <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.3.0/angular-ui-router.js"></script>
\t \t <script src="app.js"></script>
\t </head>
\t <body ng-app="foo">
\t \t <div class="root-view" ui-view="root"></div>
\t \t <pre id="errors" style="color: #e22; margin-top: 20px;"></pre>
\t </body>
</html>
謝謝!當然你是對的。 我在https://docs.angularjs.org/guide/directive中被錯誤的措辭拋棄了,例如「除非找到**指定的控制器**,否則會拋出錯誤」,「A ^前綴會使該指令在其自己的元素或其父母上尋找**控制器**。 https://docs.angularjs.org/api/ng/service/$compile上的文檔要好得多 –
@StephenFriedrich是的,這是我給予某人在兩天內混合使用的第二個答案。別擔心,你並不孤單:) – Walfrat
我可以'要求:'^^ uiView''?一個錯誤說uiView無法找到。爲什麼? – Shawn