我有一个由 Controller / View 使用的服务,当在 View 中按下按钮时,它会触发服务中的一个方法。此服务需要访问该 View 中 TextArea 的值。
目前我有:
在服务内:
cancelClick: function() {
console.log(angular.element('commentText').val());
},
然后在 View 中:
<textarea class="cancel-comment form-control" rows="8" id="commentText" placeholder="Notes" x-ng-model="cancelNotes"></textarea>
<div class="text-center">
<button type="button" class="btn btn-danger btn-cancel" id="cancel-order" ng-click="orderService.cancelClick()">{{'CANCEL THIS ORDER' | translate}}</button>
</div>
现在按钮单击可以正常工作,但是 console.log
打印出 未定义
。
从 View 中获取值的正确方法是什么?
最佳答案
在 Angular 服务中不应具有访问权限,也不应操作 DOM 对象。相反,您可以使用 Controller 绑定(bind)到 View ,并仍然使用您的服务存储/操作文本:
<强> The Plunker
标记
<div class="form-group">
<h3 class="text-success">Test Area</h3>
<textarea class="form-control" rows="8" id="commentText" placeholder="Notes" ng-model="mainCtrl.text"></textarea>
</div>
<button type="button" class="btn btn-success" ng-click="mainCtrl.saveToLocalStorage()">Save Changes</button>
JS
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['tempDataStorageService', function(tempDataStorageService) {
var myCtrl = this;
myCtrl.text = angular.copy(tempDataStorageService.text);
myCtrl.localStorage = tempDataStorageService;
myCtrl.saveToLocalStorage = function () {
tempDataStorageService.text = angular.copy(myCtrl.text);
}
}]);
app.factory('tempDataStorageService', function() {
// The service object
var storage = this;
storage.text;
// return the service object
return storage;
});
关于javascript - 在 AngularJS 服务中获取 TextArea 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36403612/