Per Larsen
Per Larsen

Reputation: 1189

How to call a javascript function and alter a variable in an Angular controller?

I am trying to learn angular.js. I am just trying to understand the basic concepts. I have taken an example from W3Schools and tried to alter it to display a variable that can be incremented by the click of a button. I'm trying to keep the different elements as separate as possible so I can understand how everything connects. I have left a portion of the example in just be be sure enerything is working as it is suppose to. Here is my code that doesn't work.

LearningAngular.js

    var myApp = angular.module("myApp", []);
    myApp.controller("myController", myController);

    function myController($scope) {
        $scope.firstName = "John";
        $scope.counter = 0;    
    }

function start_counting(){
     myController.counter ++;
}

index.html

<!DOCTYPE html>

<html>
<head>
    <title>Learning Angular</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script type="text/javascript" src="LearningAngular.js"></script>
</head>

<body ng-app="myApp" ng-controller="myController">

    First Name: <input type="text" ng-model="firstName"><br>
    <br>
    Full Name: {{firstName}}<br>

    <button onclick="start_counting()">Start Counting</button><br>
    Counter: <span>{{counter}}</span>


</body>
</html>

Upvotes: 0

Views: 62

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Keep all the functions needed inside the main component function. You need to have access to $scope in order to change the view

  function myController($scope) {
        $scope.firstName = "John";
        $scope.counter = 0; 

      // iniitalize counter when controller is initialized
       start_counting();

        // a simple function only used in controller, not view
       function start_counting(){
          $scope.counter ++;
       }         

    }

If you need to use that function in the view for example in an ng-click then just do:

$scope.start_counting = start_counting;// pass function reference to $scope

Don't use onclick in the view ... use ng-click so you can access methods in controller scope. onclick only has access to global window variables and functions...not angular scoped ones

<button ng-click="start_counting()">Start Counting</button><br>

Upvotes: 1

Alon Eitan
Alon Eitan

Reputation: 12025

The function should be declared in the $scope's scope:

function myController($scope, $interval) {
    $scope.firstName = "John";
    $scope.counter = 0;    
    $scope.start_counting = function(){
           $scope.counter ++;
     };
   $interval(function() {
       $scope.start_counting();
   }, 1000);
}

Upvotes: 1

Related Questions