2016-05-10 99 views
0

我正在尝试使用AngularJS保存在textarea上的文本输入。在AngularJS中保存textarea文本

每次更改文本时我都需要保存这些值,并将这些值存储在服务中,以便稍后可以将其提取到数据库中。

我在我的form.html textarea的看起来如下:

<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" placeholder="Additional comments"></textarea> 

<!-- This isnt displaying anything --> 
{{newMessage}} 
<!-- This isnt displaying anything -->   
{{myTextArea}} 

在我控制我实现一个$表()在NG-模型如下,但是这是行不通的。我也尝试实施ng-change,但是没有成功。

$scope.$watch("newMessage", function (newVal, oldVal) 
{ 
    console.log("Getting here..."); // Getting here 

    if (newVal !== oldVal) 
    { 
     // This block is never executed 
     $scope.myTextArea = "This is new values: " + newVal; 

     // Save the new textarea text to service 
     save($scope.myTextArea); 
    } 
}); 

$scope.save = function() 
{ 
    // This block never executed 
    console.log("sharedProperties.setAdditionalCommentsText(): "); 
    sharedProperties.setAdditionalCommentsText($scope.myTextArea); 

    console.log("sharedProperties.getAdditionalCommentsText: " + sharedProperties.getAdditionalCommentsText()); 
}; 

而且我保存textarea的文字像下面的服务:

app.service('sharedProperties', function() 
{ 
    // Initialise the Variables 
    var additionalCommentsText = ""; 

    return 
    { 
     // Get and set the Additional Comments Text 
     getAdditionalCommentsText: function() 
     { 
      return additionalCommentsText; 
     }, 
     setAdditionalCommentsText: function(value) 
     { 
      additionalCommentsText = value; 
     } 
    } 
} 
+1

你在你的控制器定义'$ scope.newMessage'?它应该是'$ scope.ave($ scope.myTextArea)'不'保存($ scope.myTextArea)''在'$ scope.watch'中 –

+0

不,我没有定义它,但它也没有帮助。阅读另一个SO帖子将其删除,因此它不再存在。 – heyred

+1

'$ scope.newMessage'应该被定义,并且分配给'$ scope.save'的函数应该有一个参数。 –

回答

1

我做我的电脑和它的作品,

在控制器:

$scope.newMessage = ''; 
$scope.$watch('newMessage', function(newValue, oldValue) { 
    if (newValue !== oldValue) { 
     console.log('do save staff'); 
    } 
});   
在HTML

<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" placeholder="Additional comments"></textarea> 

输出:

enter image description here

2

试一试,用ng-change

<textarea class="textarea" style="width: 90%; margin-left: 5%" rows="7" maxlength="100" ng-model="newMessage" ng-change="save(newMessage);" placeholder="Additional comments"></textarea> 

JS

$scope.save = function (message) { 
    console.log(message); 
}; 
相关问题