3

I am newbie angularjs developer. I have,

var app = angular.module('myapp', []);
app.controller('ProductCtrl', ['$scope', '$sce', function ($scope, $sce) {
    $scope.products = myapp.products;
    $scope.pager = $sce.trustAsHtml(myapp.pager);
    $scope.getProducts = function($event) {
        $event.preventDefault();
        var $link = $($event.target);
        var url = $event.target.href;
        $.getJSON(url, function(response) {
            $scope.$apply(function() {
                $scope.products = response.products;
                $scope.pager = $sce.trustAsHtml(response.pager);
            });
            history.pushState(response, "Index", url);
        });
    };
}]);
$(window).bind("popstate", function (e) {
    console.log(e.originalEvent.state);// I need scope here
});

You can see that clicking will call getProducts methods which will update $scope.products and $scope.pager. I am also doing history.pushState. Now, what I want, whenever user click the back button, I need to update $scope.products and $scope.pager again. Is that possible with AngularJS?

Rathma
  • 1,196
  • 2
  • 33
  • 65
Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

2 Answers2

4

You are mixing Jquery and Angularjs. Now this can and often has been done as many useful libraries require Jquery.

But you are recreating a lot of Angular's functionality with Jquery here.

Firstly you should look at Angular's $routeProvider and $locationProvider.html5Mode(true); which will enable your app navigation and history really easily. Here is a good blog post to start with on this topic by Scotch.io.

Next up you are using Jquery's Ajax, instead use Angular's $http inside a service, which when used in a Single Page Application (explained in the above post) will allow your entire data to be persisted across page reloads (which become template swaps).

In general, go through the entire AngularJS Tutorial and look at how you can apply it's methodology to your app. It will save you a lot of time, as Angular is well thought out and deals with all of these issues you are trying to tackle right now. It does have a steep learning curve but persevere. You can always leave out the test driven development(which they push in the tutorial) for now and focus on the core concepts and features.

Also look at this popular post on moving from Jquery to Angular, it may help: "Thinking in AngularJS" if I have a jQuery background?

Community
  • 1
  • 1
caffeinated.tech
  • 6,428
  • 1
  • 21
  • 40
0

For now I am fixing this using,

var $scope = angular.element('[ng-controller=ProductCtrl]').scope();

until I learn more.

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322