Search code examples
angularjsangularjs-scopeangular-ui-router

How to make ui-sref work inside JQuery loaded HTML DOM


I am new to Angular JS. What I am doing is to bind ui-sref on JQuery loaded data. All the JQuery plugins and rest of Angular is working perfectly fine. What I have for now looks like:

app.controller("FeedController", ['$scope', '$http', '$compile', function($scope, $http,  $compile) {

            var feed = this;    
            feed.years = [];

            feed.getYears = function() {
                $http.get('/timeline/years').success(function(data) {
                    feed.years = data;
                });
            };
            feed.getYears();

            $scope.$watch('sliderWrapper', function() {

                applyTreemap(); // jquery treemap layout plugin
                applyKnob(); // jquery knob plugin

            });

            // I was trying to compile externally loaded DOM by that plugin here.
            // Didn't figure out how to do it.
            $scope.refresh = function() {
                // #slider is main content wrapper
                $compile( $("#slider").html())($scope);
            };


        }]);

Please don't suggest to use AngularJS instead of JQuery. Actually this is a Treemap Layout plugin and already integrated into existing website.


Solution

  • Okay so $compile works as in my code but there are some problems I faced. Here's one. Consider the following code.

    <div id="slider">
      <div ng-repeat="slide in slides">
         <!-- html loaded by jquery ajax will go here -->
      </div>
    </div>
    

    In angular I was doing

    $compile( $("#slider").html())($scope);
    

    So, I was compiling html of #slider in angular and it already has angular bindings besides ajax loaded content. So angular compiler will re-render them and you will run into problems.

    So keep in mind that you never $compile html that already has angular bindings.

    So I solved my problem by putting

    href="#/path/to/state"

    instead of doing

    ui-sref="home.child()"

    into ajax loaded conent.

    Sometimes you know something and its not in your mind when you are stuck. :-D