AngularJS 在 ng-click 上更改范围变量

AngularJS change scope variable on 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

试试这个

<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 方法,所以它只会初始化对象一次。

首先像这样在控制器中初始化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']);

注:

first click on the 'click me' span and value is set into the array and click on the next span for your console it. your console only works on clicking edit.showMyVar(); function

Fiddle

您需要做一些更改 --

You can not keep an assignment code in {{ }} since this code renders frequently . so you will not get the actual value.

Working plunker..

    <!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. 您不能在 {{ }} 中保留分配代码,因为此代码经常呈现。所以你不会得到实际价值。
  2. 我在加载文档应用程序之前遇到的另一个问题是引导。