[英]How to change variable when i press button in angularJS?
如何通過使用Angular按鈕更改視圖中的某個變量?
例如視圖:
<div id="someDiv" ng-app="myApp" ng-controller="myCtrl">
<p ng-bind="firstname"></p>
<button type="button" ng-click="changeValue('Joe')"></button>
</div>
腳本:
var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope){
$scope.firstname = "Johny";
$scope.changeValue= function(param) {
$scope.firstname = param;
}
});
我希望當我按下按鈕然后Johny將成為Joe(如參數中所示)。 在我點擊按鈕的那一刻沒有任何反應
@EDIT好的,我知道問題出在哪里。 這在我的主要div工作正常。 但它不適用於我的第二個div:
我點擊其他按鈕運行下面的腳本,這個腳本改變了我的div
function show(div_id){ //div_id is `someDiv`
document.getElementById('main_place').innerHTML = document.getElementById(div_id).innerHTML;
}
但為什么角度腳本不適用於這個div?
加
$scope.changeValue = function(newVal) {
$scope.firstname = newVal;
}
並在html上輸入<p>{{firstname}}<p>
在控制器中嘗試這個:
$scope.changeValue = function(changeName)
{
$scope.firstname = changeName;
};
在視圖中:
<p>{{firstname}}</p>
請檢查一下。
HTML:
<div id="someDiv" ng-app="myApp" ng-controller="myCtrl">
<p ng-bind="firstname"></p>
<button type="button" ng-click="changeValue('Joe')"></button>
</div>
JS:
var myApp = angular.module('myApp',[]);
myApp.controller("myCtrl", function($scope){
$scope.firstname = "Johny";
$scope.changeValue= function(param) {
$scope.firstname = param;
}
});
我用你的問題創建了一個工作示例:
這是一個有效的例子
var app = angular.module('myApp', []);
app.controller("myCtrl", function($scope){
$scope.firstname = "Johny";
$scope.changeValue = function(param) {
$scope.firstname = param;
}
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script> <link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div id="someDiv" ng-app="myApp" ng-controller="myCtrl">
<p ng-bind="firstname"></p>
<button type="button" ng-click="changeValue('Joe')">Click</button>
</div>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.