如何在 Angular js 中从 html 调用功能控制器?
how to call function controller from html in Angular js?
我想在控制器中执行一个 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');
}
}
})();
ng-click="helloWorld()
将尝试调用此处未定义的 $scope.helloWorld()
函数。
helloWorld 函数链接到您的控制器对象,而不是 Angular 范围。
你必须为你的控制器设置一个别名,比如ng-controller="indexController as index"
,你可以这样调用你的helloWorld函数:ng-click="index.helloWorld()"
.
要从您的控制器访问模板中的函数或数据,您必须在 $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>
我想在控制器中执行一个 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');
}
}
})();
ng-click="helloWorld()
将尝试调用此处未定义的 $scope.helloWorld()
函数。
helloWorld 函数链接到您的控制器对象,而不是 Angular 范围。
你必须为你的控制器设置一个别名,比如ng-controller="indexController as index"
,你可以这样调用你的helloWorld函数:ng-click="index.helloWorld()"
.
要从您的控制器访问模板中的函数或数据,您必须在 $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>