如何调用javascript函数并更改角度控制器中的变量?

如何调用javascript函数并更改角度控制器中的变量?,javascript,html,angularjs,Javascript,Html,Angularjs,我正在努力学习angular.js。我只是想了解基本概念。我从W3Schools中获取了一个示例,并尝试对其进行修改,以显示一个可以通过单击按钮递增的变量。我试图尽可能地把不同的元素分开,这样我就可以理解每件事是如何联系在一起的。我在这里留下了一部分示例,只是要确保enerything按预期的方式工作。这是我的代码,不起作用 LearningAngular.js index.html 学习角度 名字: 全名:{{firstName}} 开始计数 计数器:{{Counter}} 函数应在$

我正在努力学习angular.js。我只是想了解基本概念。我从W3Schools中获取了一个示例,并尝试对其进行修改,以显示一个可以通过单击按钮递增的变量。我试图尽可能地把不同的元素分开,这样我就可以理解每件事是如何联系在一起的。我在这里留下了一部分示例,只是要确保enerything按预期的方式工作。这是我的代码,不起作用

LearningAngular.js

index.html


学习角度
名字:

全名:{{firstName}}
开始计数
计数器:{{Counter}}
函数应在$scope的作用域中声明:

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

函数应在$scope的作用域中声明:

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

将所需的所有功能保留在主组件功能中。您需要有权访问$scope才能更改视图

  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 ++;
       }         

    }
如果您需要在视图中使用该功能,例如在
ng中单击
,则只需执行以下操作:

$scope.start_counting = start_counting;// pass function reference to $scope
不要在视图中使用
onclick
。。。使用
ng单击
,以便可以访问控制器范围内的方法
onclick
只能访问全局窗口变量和函数,不能访问角度范围的变量和函数

<button ng-click="start_counting()">Start Counting</button><br>
开始计数

将所需的所有功能保留在主组件功能中。您需要有权访问$scope才能更改视图

  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 ++;
       }         

    }
如果您需要在视图中使用该功能,例如在
ng中单击
,则只需执行以下操作:

$scope.start_counting = start_counting;// pass function reference to $scope
不要在视图中使用
onclick
。。。使用
ng单击
,以便可以访问控制器范围内的方法
onclick
只能访问全局窗口变量和函数,不能访问角度范围的变量和函数

<button ng-click="start_counting()">Start Counting</button><br>
开始计数

我会试一试]谢谢。下一个问题是如何使用say setInterval使其自动递增变量。@PerLarsen-添加了interval示例,请注意,您需要向控制器功能注入
$interval
。您应该将其作为不同的问题提出,或者更新您现有的问题。不用担心,我将接受您展示的内容,看看是否可以首先解决它。谢谢你的帮助。如果我不懂,我会发布一个新问题。我会试试]那工作谢谢。下一个问题是如何使用say setInterval使其自动递增变量。@PerLarsen-添加了interval示例,请注意,您需要向控制器功能注入
$interval
。您应该将其作为不同的问题提出,或者更新您现有的问题。不用担心,我将接受您展示的内容,看看是否可以首先解决它。谢谢你的帮助。如果我不懂,我会发布一个新问题。只是添加了对原因的解释只是添加了对原因的解释