0

i want execute a hello world function into a controller (call from html with button click), but i cant call this and i do not know why it does not work because not any show a error.

html code:

<html ng-app="app">


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

and controller 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');
    }
}
})();
2
  • did you try onclick="helloWorld()" instead of ng-click="helloWorld()" in your html code? Commented Oct 31, 2017 at 23:53
  • Is that the directive ng click is typical of angular, and is the one that should use Commented Oct 31, 2017 at 23:56

2 Answers 2

3

ng-click="helloWorld() will try to call $scope.helloWorld() function, that is undefined here.

helloWorld function is linked to your controller object, not to the Angular scope.

You have to set an alias of your controller, like ng-controller="indexController as index", and you will can call your helloWorld function like this: ng-click="index.helloWorld()".

Sign up to request clarification or add additional context in comments.

Comments

0

To access functions or data in the template from your controller, you must define the function or value on the $scope object. Anything you define on the $scope object you can use in the template.

Instead of vm.helloWorld = helloWorld; try $scope.helloWorld = helloWorld;

In the same way, you can access data from your controller and display it in the template.

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>

2 Comments

You can refer to the scope as a this object if you use a Controller as Class syntax, his code was fine, he just didn't declare his controller correctly
@AlekseySolovey Ah I see, I wasn’t aware of that syntax, thanks for the clarification.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.