我有一个控制器/视图使用的服务,当在视图中按下按钮时它会触发服务中的方法。此服务需要访问该视图中TextArea的值。
目前我有:
服务中的:
cancelClick: function() {
console.log(angular.element('commentText').val());
},
然后在视图中:
<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
打印undefined
。
从视图中获取值的正确方法是什么?
答案 0 :(得分:1)
在角度服务中不应该具有访问权限,也不应该操纵DOM对象。相反,您可以使用控制器绑定到您的视图,并仍然使用您的服务存储/操作文本:
<强> 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;
});
答案 1 :(得分:0)
commentText is Id
在您看来。
cancelClick: function() {
console.log(angular.element('#commentText').val());
},