CudB
CudB

Reputation: 83

JavaScript not updating part of $scope variable

for reference, I am using a MEAN stack with Restangular for API calls.

The post.tags variable is an array of strings that my script is supposed to update (along with the rest of the object). The problem is, the tags variable is not updating while other variables within the post object have no trouble.

I join the array into a single string so that it can be easily modified in the view before updating, but I suspect that line is also what is causing it to not update correctly. I have a console log inserted to verify that $scope.tags did not update when I click the save button in the view. A little two-way binding in the view also shows that it does get updated prior to pressing save, but once that button is pressed, it reverts back to the original value.

This seems like a fairly trivial problem, but I am having trouble finding a solution. Any help would be greatly appreciated.

post-edit.js

.controller('PostEditCtrl', function ($scope, $location, $routeParams, Post) {       
  $scope.editPost = true;
  $scope.post = {};
  Post.one($routeParams.id).get().then(function(post) {
    $scope.post = post;
    $scope.tags = $scope.post.tags.join();
    $scope.savePost = function() {
      $scope.post.tags = $scope.tags.replace(/[\s]/g, '').split(',');
      console.log($scope.tags);
      $scope.post.save().then(function() {
        $location.path('/post/' + $routeParams.id);
      });
    };
  });
});

post-edit.html

...
<div class="form-group">
  <label for="content" class="control-label">Tags</label>
  <input type="text" ng-model="tags" class="form-control" id="tags" placeholder="Enter a comma separated list of tags">
  <p>{{tags}}</p>
</div>
...

Upvotes: 1

Views: 99

Answers (1)

CudB
CudB

Reputation: 83

Fixed my problem by not using the temporary variable $scope.tags at all and just using $scope.post.tags. Final JS file is below:

post-edit.js

.controller('PostEditCtrl', function ($scope, $location, $routeParams, Post) {       
  $scope.editPost = true;
  $scope.post = {};
  Post.one($routeParams.id).get().then(function(post) {
    $scope.post = post;
    $scope.post.tags = $scope.post.tags.join();
    $scope.savePost = function() {
      $scope.post.tags = $scope.post.tags.replace(/[\s]/g, '').split(',');
      $scope.post.save().then(function() {
        $location.path('/post/' + $routeParams.id);
      });
    };
  });
});

Upvotes: 1

Related Questions