我有一个表单,其中两个输入字段(session.email
和 session.psw
)绑定(bind)到 LoginController.session
属性。当我单击重置按钮时,我调用 LoginController.reset()
函数。
我想利用变量sessionDefault(空)
来明确 session 属性。然而,它只能工作一次,如果我重置表单两次,sessionDefault
是未定义
。
如何将其设置为 Controller 的常量属性?
app.controller('LoginController', function ($scope)
{
this.session={};
var sessionDefault=
{
email : "",
psw: ""
};
this.reset = function()
{ this.session = sessionDefault; };
});
最佳答案
试试这个
对于重置功能,只需使用 sessionDefault 副本重置它,如下所示
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
这里this
指的是 Controller 实例
请注意,我使用了 var vm = this;
,然后使用应公开且可数据绑定(bind)到 View 的成员来装饰 vm
。 vm
仅表示 View 模式
这对我来说有 3 件事。
提供了在我的 Controller 中创建绑定(bind)的一致且可读的方法
消除了处理此范围或绑定(bind)的任何问题(即嵌套函数中的闭包)
从 Controller 中删除
$scope
除非我明确需要它用于其他用途
<强> Working Demo
脚本
var app = angular.module('myApp', []);
app.controller('LoginController', function ($scope) {
var vm = this;
vm.session = {};
var sessionDefault = {
email: "",
psw: ""
};
vm.reset = function () {
vm.session = angular.copy(sessionDefault);
};
});
html
<div ng-app='myApp' ng-controller="LoginController as login">
Email:<input type="text" ng-model="login.session.email"/>{{login.session.email}}
<br>
Psw:<input type="text" ng-model="login.session.psw"/>{{login.session.psw}}
<br>
<button ng-click="login.reset()">Reset</button>
</div>
看看这个美丽的东西。
关于javascript - Angular Controller 的属性在其功能之外不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29674369/