Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Attempted to assign to readonly property - when typing in a text field

I recently updated my Angular from 1.5.x to 1.6.4 and now, when I go to a form, I get the below error message whenever I try to type something up in the form/textbox:

TypeError: Attempted to assign to readonly property.

This is my controller:

mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http){

$scope.post = '';
$scope.postCreated = false;

$scope.makeNewPost = function() {

    $http.post('/api/post', {
        title:          $scope.post.title,
    })
    .then(function(res){
        $scope.postCreated = true;
        //extra code not related to the form itself...
  };
}]);

My HTML looks like this:

<form ng-submit="makeNewPost()">
<div class="form-group">
    <label for="title" class="control-label">Title</label>
    <input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
</div>

<input type="submit" value="Submit">
</form>

I looked this error up and everything I am seeing has nothing to do with what my set up is like.

Please help me out on this. I don't know where to go from here.

Thanks

like image 340
Shayan Khan Avatar asked May 04 '17 15:05

Shayan Khan


People also ask

How do I fix attempted to assign a readOnly property?

The error "Cannot assign to read only property of object" occurs when we try to change a property of an object that has been frozen or when a property has been defined with Object. defineProperties() . To solve the error, create a copy of the object or array, or set the property to writable .

What is read only Error in JavaScript?

The JavaScript strict mode-only exception "is read-only" occurs when a global variable or object property that was assigned to is a read-only property.


1 Answers

Try this...

you have initialized $scope.post = ''; as a string. But that should be $scope.post = {}; an object.

var mainApp = angular.module('app', []);
mainApp.controller('newPostController', ['$scope', '$http', function($scope, $http) {

  $scope.post = {};
  $scope.postCreated = false;

  $scope.makeNewPost = function() {
    console.log($scope.post.title);
    $http.post('/api/post', {
        title: $scope.post.title,
      })
      .then(function(res) {
        $scope.postCreated = true;
        //extra code not related to the form itself...
      });
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app='app' ng-controller='newPostController'>
  <form ng-submit="makeNewPost()">
    <div class="form-group">
      <label for="title" class="control-label">Title</label>
      <input type="text" autocomplete="off" class="form-control" ng-model="post.title" id="title" required="required">
    </div>
    <input type="submit" value="Submit">
  </form>
</div>
like image 54
Sankar Avatar answered Nov 10 '22 08:11

Sankar