【问题标题】:how to call function controller from html in Angular js?如何在 Angular js 中从 html 调用函数控制器?
【发布时间】:2018-04-13 06:11:56
【问题描述】:

我想在控制器中执行一个 hello world 函数(通过单击按钮从 html 调用),但我不能调用它,我不知道为什么它不起作用,因为没有任何显示错误。

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');
    }
}
})();

【问题讨论】:

  • 您是否尝试过在您的 html 代码中使用 onclick="helloWorld()" 而不是 ng-click="helloWorld()"?
  • 指令 ng click 是不是 Angular 的典型特征,是应该使用的指令

标签: javascript angularjs button controller config


【解决方案1】:

ng-click="helloWorld() 将尝试调用$scope.helloWorld() 函数,此处未定义。

helloWorld 函数链接到您的控制器对象,而不是 Angular 范围。

你必须为你的控制器设置一个别名,比如ng-controller="indexController as index",你可以像这样调用你的helloWorld函数:ng-click="index.helloWorld()"

【讨论】:

    【解决方案2】:

    要从控制器访问模板中的函数或数据,您必须在 $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>

    【讨论】:

    • 如果您使用 Controller as Class 语法,您可以将范围称为this 对象,他的代码很好,只是他没有正确声明他的控制器
    • @AlekseySolovey 啊,我明白了,我不知道那个语法,谢谢你的澄清。
    猜你喜欢
    • 2014-10-23
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多