[英]AngularJS change scope variable on ng-click
我尝试在ng-click
在模板中设置范围变量, ng-click
在控制器中读取它。 例:
HTML:
<section id="editCtrl" data-ng-controller="EditCtrl as edit">
{{ edit.myVar = []; "" }}
Click the following buttons:<br>
<span data-ng-click="edit.myVar['entry'] = 'test'">Click me</span>
<span data-ng-click="edit.showMyVar();">Show MyVar in console</span>
</section>
JS:
// This controller is just for the example - I would never add a controller variable within the template
var app = angular.module("app", []);
app.controller("EditCtrl", function(){
var edit = this;
edit.showMyVar = function(){
console.log(edit.myVar);
};
});
但是变量“edit.myVar”仍然是一个空数组。 我究竟做错了什么? 在我的解释中,这是一个有效的ng-click表达式。
实例: JSFiddle
你需要做几件改变 -
由于此代码经常呈现,因此您无法在
{{ }}
保留分配代码。 所以你不会得到实际价值。
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
<style>span:nth-of-type(1){background:yellow;}
span:nth-of-type(2){background:red;}</style>
</head>
<body>
<section id="editCtrl" ng-controller="EditCtrl as edit">
Click the following buttons:<br>
<button ng-click="edit.myVar['entry']='test'">Click me</button>
<button ng-click="edit.showMyVar()">Show MyVar in console</button>
</section>
<script>angular.bootstrap(document, ['app'])</script>
</body>
</html>
Js文件
// This controller is just for the example - I would never add a controller variable within the template
var app = angular.module("app", []);
app.controller("EditCtrl", function(){
var edit = this;
edit.showMyVar = function(){
alert(JSON.stringify(edit.myVar));
};
});
代码问题:
{{ }}
保留分配代码。 所以你不会得到实际价值。 初始化edit.myVar = {'entry' : ''};
在控制器中首先这样
var app = angular.module("app", []);
app.controller("EditCtrl", function(){
var edit = this;
edit.myVar = {'entry' : ''};; // initailize the array here
edit.showMyVar = function(){
console.log(edit.myVar);
};
});
angular.bootstrap(document, ['app']);
注意:
首先单击“click me”span并将值设置到数组中,然后单击控制台的下一个span。 您的控制台仅适用于单击
edit.showMyVar();
功能
试试这个
<section id="editCtrl" ng-init="edit.myVar = [];" data-ng-controller="EditCtrl as edit">
Click the following buttons:<br>
<span data-ng-click="edit.myVar['entry'] = 'test'">Click me</span>
<span data-ng-click="edit.showMyVar();">Show MyVar in console</span>
更新:我认为你的对象一次又一次被初始化。 我使用了ng-init方法,所以它只会初始化一次对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.