AngularJS not updating view when used in wordpress admin widget form

I’m trying to use AngularJS to build some custom form components for a wordpress widget’s admin view, but I cant seem to get angular firing on all cylinders.

I’m including angular and my custom JS in my plugin as so:

Read More
wp_enqueue_script( 'angular', plugin_dir_url( __FILE__ ) . '/js/angular.min.js' );
wp_enqueue_script( 'featured_admin', plugin_dir_url( __FILE__ ) . '/js/admin.js' );

In the form function of my WP_Widget class, I’ve added the following markup:

<div ng-app='MyApp'>
    <div class="my-form" ng-controller="FormController">
        {{hello}}
    </div>
</div>

And then in my /js/admin.js file I have the following javascript:

var app = angular.module('MyApp', []);

app.controller('FormController', ['$scope', function ($scope) {
    console.log('do something');
    $scope.hello = "hello world";
}]);

When I run the above code in wordpress, I get ‘do something’ in the console, so I believe the module and controller are all hooked up correctly. However, the view is outputting {{hello}} rather than the variable in the scope.

Has anybody had any experience with getting angular up and running in wordpress? I’m inclined to believe it has something to do with how wordpress renders it’s admin forms. Is there a way to defer the execution of the angular code, until I’m certain wordpress has rendered all of the forms?

Related posts

Leave a Reply

1 comment

  1. Use manual boostrapping as an alternative:

    /* Create script element */
    var script = document.createElement('script');
    /* Set src */
    script.src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js";
    /* Append to head */
    document.getElementsByTagName("head")[0].appendChild(script);
    
    function dothis()
      {    
      //template string
      var html = "<div class=u0022my-formu0022>{{$hello}}</div>";
      //template object
      var template = angular.element(html);
      //template transformer
      var compiler = angular.injector(["ng"]).get("$compile");
      //template result
      var linker = compiler(template);
      //scope object
      var scope = angular.injector(["ng"]).get("$rootScope");
      //scope assignment
      scope.hello = "hello world";
      //scope binding
      var result = linker(scope)[0];
    
      /* Append result to body */
      document.body.appendChild(result);
    
      /* Render */
      angular.bootstrap(document, ['ng']);
      }
    
    script.onload = dothis;