[英]How to call a javascript function and alter a variable in an Angular controller?
我正在嘗試學習angular.js。 我只是想了解基本概念。 我以W3Schools為例,嘗試更改它以顯示一個變量,該變量可以通過單擊按鈕來增加。 我試圖將不同的元素盡可能地分開,以便我能理解一切之間的聯系。 我只保留了一部分示例,只是為了確保按預期進行工作。 這是我的代碼不起作用。
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>
該函數應在$ 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-click
則只需執行以下操作:
$scope.start_counting = start_counting;// pass function reference to $scope
不要在視圖中使用onclick
...使用ng-click
這樣您就可以訪問控制器范圍內的方法。 onclick
只能訪問全局窗口變量和函數,而不能訪問角度范圍的變量和函數。
<button ng-click="start_counting()">Start Counting</button><br>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.