1

I'm currently working on a jQuery app and trying to gradually change it to angularJS. I don't want to change all existing jQuery code. The jQuery code makes an ajax call and updates a variable depending on the ajax result. I need this result in my angular scope. I tried to create a hidden input, or input with display none and update it with jQuery $('#accountId').val(value) :

<input type="text" ng-model="account.accountId" style="display:none" id="accountId" name="accountId">

But my $scope variable $scope.account.accountId doesn't get updated.

I also tried things like ng-value, jquery trigger input, ...

Thanks

Komo
  • 2,043
  • 1
  • 22
  • 35
  • 2
    I think this is a bad idea. See here: http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background/15012542 – 11684 Jan 24 '15 at 22:33
  • 1
    Concept is really backwards due to the way angular works. You don't slowly integrate angular into jQuery page without a lot of problems due to the way angular manages the DOM....after *document.ready*. Will have to use a lot of `$apply()` also – charlietfl Jan 24 '15 at 22:37
  • You should be using Angular form validations and ng-messages instead – Wayne Ellery Jan 24 '15 at 22:43
  • Yes that's true. I have started rewriting whole existing jQuery code in angularJS and it's much cleaner and faster. I think I will be doing the same here for the ajax part. – Komo Jan 24 '15 at 22:43

1 Answers1

2

As others have said, this isn't ideal. However, it also shouldn't be too big of a problem as long as you keep your code modular. Try creating a service to manage your jQuery ajax requests, and then inject that service as a dependency inside your controller.

A simple example might look like:

angular.module('app', [])

  // jQuery managed ajax service
  .service('AccountSvc', function() {
    var BASE_URL = '/accounts';

    this.getAccount = function(id) {

      // I'm assuming this returns a promise
      // haven't worked with jQuery for a while
      return $.get(BASE_URL + '/' + id);
    };

  })

  .controller('AccountsCtrl', function($scope, AccountSvc) {

    AccountSvc.get(123).then(function(account) {
      $scope.account = account;
    });

  });
tydotg
  • 631
  • 4
  • 11