我尝试在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);
};
});
然而变量&#34; edit.myVar&#34;继续成为一个空阵列。我究竟做错了什么?在我的解释中,这是一个有效的ng-click表达式。
实例:JSFiddle
答案 0 :(得分:2)
您需要做一些更改 -
由于此代码呈现,您无法在
{{ }}
中保留分配代码 经常。所以你不会得到实际价值。
<!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));
};
});
您的代码出现问题:
{{ }}
中保留作业代码。所以你不会得到实际值。答案 1 :(得分:1)
首先在控制器中初始化li:nth-child(odd) {width: 50%; float: left;}
li:nth-child(even) {width: 50%; float: right;}
ul.sub li {width: 100%;}
,如下所示
<ul>
<li>Test 1</li>
<li>Test 2
<ul class="sub">
<li>Test2.1</li>
<li>Test2.2</li>
<li>Test2.3</li>
<li>Test2.4</li>
<li>Test2.5</li>
</ul>
</li>
<li>Test 3</li>
<li>Test 4</li>
<li>Test 5</li>
<li>Test 6</li>
</ul>
注意:
首先点击“点击我”。 span和value设置在数组中 然后单击控制台的下一个跨度。你的控制台 可以点击
edit.myVar = {'entry' : ''};
功能
答案 2 :(得分:-1)
试试这个
<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方法,所以它只会初始化一次对象。