簡體   English   中英

為什么Angular js找不到自定義控制器

[英]why can't angular js can't find the custom controller

我在單獨的文件中創建了一個自定義的angularjs控制器,並且調用方也在單獨的文件中。 但是由於某種原因,angularjs給出的錯誤控制器未定義。 這些是文件:

test_ctrl.js:

function test_ctrl($scope, $rootScope, apiSrvc, $mdDialog) {

    $scope.hide = function() {$mdDialog.hide();};
    $scope.cancel = function() {$mdDialog.cancel();};

  }

index.html:

<button id="testbutton" ng-click="openModal($event)">open modal</button>

index.js:

// Open the Modal // 
  $scope.openModal = function(ev) { 
    $mdDialog.show({
      controller: test_ctrl,  
      templateUrl: '/views/testview/testmodal.html',
      parent: angular.element($('.some_parent_class')),
      targetEvent: ev,
      clickOutsideToClose:true,
      locals: {},
      onRemoving: function (event, removePromise) {
      }
    });
  };
  //*/ 
});

testmodal.html:

<md-dialog>
    <md-dialog-content>
        testing content
    </md-dialog-content>
    <md-dialog-actions layout="row">
        <md-button ng-click="cancel()">Close</md-button>
    </md-dialog-actions>
</md-dialog>

好的,總結一下過程,index.html中的按鈕應該打開一個角度模態對話框。 所以對於按鈕的index.html我列入“NG-點擊=” openModal($事件)”觸發角事件,打開角度模式的。我不知道我丟失或做錯了,但在控制台單擊按鈕時,出現““ test_ctrl”未在angular中定義...“錯誤。我在做什么錯?

編輯好了另一種方式來繞過它是包含在同一文件index.js控制器定義功能,但我真的希望包括在openModal參數外部控制器文件的位置一樣,你可以用模態模板位置(templateUrl: '/views/testview/testmodal.html')。 控制器文件的位置是否有參數?

控制器功能定義需要在index.js加載之前定義,因此在index.html中,您需要在index.js之前加載test_ctrl.js

較干凈的替代方法是將控制器功能導入index.js

我將控制器放在外部文件中,並使用openModal angular方法對其進行調用。 有沒有一種方法可以在openModal參數中定義控制器文件的位置?

將控制器定義為模塊的一部分:

angular.module("test",[])
.controller("test_ctrl",
  function test_ctrl($scope, $rootScope, apiSrvc, $mdDialog) {
    $scope.hide = function() {$mdDialog.hide();};
    $scope.cancel = function() {$mdDialog.cancel();};
})

在主模塊中,將其聲明為依賴項:

angular.module("app",['test'])

在模式中,使用字符串調用:

  $scope.openModal = function(ev) { 
    $mdDialog.show({
      controller: ̶t̶e̶s̶t̶_̶c̶t̶r̶l̶,̶ "test_ctrl",  
      templateUrl: '/views/testview/testmodal.html',
      parent: angular.element($('.some_parent_class')),
      targetEvent: ev,
      clickOutsideToClose:true,
      locals: {},
      onRemoving: function (event, removePromise) {
      }
    });
  };

有關更多信息,請參見AngularJS開發人員指南-模塊


當將其定義為模塊的一部分時,我可以將該代碼放入外部文件中,對嗎? 而不明確告訴angular它在哪里或是否將其包含在script標簽中?

包含模塊的文件可以按任何順序加載(在angular.js之后)。 當框架找到ng-app指令並構建應用程序時,將對依賴項進行整理。

有關更多信息,請參見John Papa AngularJS樣式指南-模塊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM