Search code examples
asp.netangularjsupdatepanel

AngularJS events with ASP.NET UpdatePanel


I'm trying to use AngularJS within an ASP UpdatePanel, very much like in this question: AngularJS with ASP.NET Updatepanel partial update

That solution also helped a lot, at least regarding the static parts, ie everything showed upon initialization.

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function (sender, args) {
                var elem = angular.element(document.getElementById("myDiv"));
                var newElem = $compile(elem)($scope);
                $scope.$apply();
                elem.replaceWith(newElem.html());
            });

Properties setup within add_endRequest() are shown properly. My problem is that all interaction is dead.

For example if I put

<div id="myDiv">
    {{testtext}}
    <div ng-init="testtext='hello world'"/>
</div>

it'll print out the string as expected. But when adding ie a click event nothing happens.

<div ng-click="testtext='hello world'">Click here</div>

Any ideas why? As I understand it the angular $compile and $scope.$apply() should apply to all angularjs functionality, but it seems not.


Solution

  • Figured it out with a little help from my friends. The problem was that only the element with my AngularJS list <div id="myDiv"> was recompiled in the add_endRequest() method. When changing this to the div holding the angularjs controller, surrounding the entire UpdatePanel section...

    <div ng-controller="UpdatePanelController" id="UpdatePanelController">
        <asp:UpdatePanel ID="UpdatePanel" UpdateMode="Conditional" runat="server">
            ...
        </asp:UpdatePanel>  
    </div>
    

    and then compiling its children...

        OneViewApp.controller("UpdatePanelController", function ($scope, $compile) {            
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
                var elem = angular.element(document.getElementById("UpdatePanelController"));
                $compile(elem.children())($scope);
                $scope.$apply();
            });
        });
    

    everything worked fine. Since UpdatePanel replaces the html, the entire controller needs to be recompiled in order for it to work properly.

    This can of course also be achieved by (re)bootstraping the angular app for every step, as suggested in another answer, but the above solution is closer to the original code and thus simpler in this case.