2017-10-31 7 views
0

私はhello world関数を(ボタンクリックでhtmlから呼び出す)コントローラに実行したいが、これを呼び出すことはできず、エラーを表示しない理由が分からない。Angular jsのhtmlからfunction controllerを呼び出す方法は?

htmlコード:

<html ng-app="app"> 


    <div ng-controller="indexController"> 
     <button type="button" ng-click="helloWorld()">action</button> 
    </div> 

とコントローラJS:

(function() { 
'use stritct'; 

angular 
.module('app',[]) 
.controller('indexController', indexController); 

indexController.inject = ['$rootScope','$scope']; 

function indexController($rootScope,$scope) { 
    var vm = this; 

    vm.helloWorld = helloWorld; 

    function helloWorld() { 
     console.log('hello'); 
    } 
} 
})(); 
+0

あなたは= "のhelloWorld()" の代わりにあなたのhtmlコードに= "のhelloWorld()を" NGクリックonclickをしようとしたのですか? – AlexWoe89

+0

ディレクティブのクリックは角の典型的なもので、使用するべきものです –

答えて

0

テンプレート内の関数またはデータにコントローラからアクセスするには、$scopeオブジェクトで関数または値を定義する必要があります。テンプレート内で使用できる$scopeオブジェクトで定義したものです。

代わりのvm.helloWorld = helloWorld;は同様に$scope.helloWorld = helloWorld;

を試してみてください、あなたは、コントローラからのデータにアクセスし、テンプレートでそれを表示することができます。

angular.module('app',[]) 
 
    .controller('indexController', indexController); 
 

 
indexController.$inject = ['$rootScope','$scope']; 
 

 
function indexController($rootScope,$scope) { 
 
    $scope.helloWorld = function() { 
 
     console.log('hello'); 
 
    } 
 
    
 
    $scope.message = 'From the controller!'; 
 
}
<html ng-app="app"> 
 
    <body> 
 
    <div ng-controller="indexController"> 
 
     <button type="button" ng-click="helloWorld()">action</button> 
 
     
 
     <p>{{ message }}</p> 
 
    </div> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    </body> 
 
</html>

+0

**コントローラをクラス**の構文として使用し、コードが正常で、彼のコントローラが正しく宣言されていない場合は、スコープを 'this'オブジェクトとして参照できます。 –

+0

@AlekseySoloveyああ、その構文を認識しています。 –

3

ng-click="helloWorld()$scope.helloWorld()関数を呼び出ししようとしますが、それはここで定義されていません。

helloWorld関数は、Angularスコープではなくコントローラオブジェクトにリンクされています。

コントローラーのエイリアスをng-controller="indexController as index"のように設定する必要があります。この場合、helloWorld関数をng-click="index.helloWorld()"と呼びます。

+0

ありがとう!!!コントローラとしての成功は成功です! –

関連する問題