marlar marlar - 6 months ago 73
AngularJS Question

AngularJS Directives for Chrome App and Android 'webview' Tags

I am in the progress of changing an existing Chrome packaged app to use Angular. So far it works well, but I am not sure how to update the UI from outside Angular, for example in response to Chrome events.

As an example, I have a webview whose current address is monitored with a loadCommit. Here is just the simplified code:

HTML fragment:

<p>Current url = {{url}}</p>


app.controller('MainController', function($scope) {
// This is the inital url
// It shows up in the HTML fragment
$scope.url = "";

Event listener:

webview.addEventListener('loadcommit', function() {
url = webview.src;
//How to update Angular framework with current value of url?

How do I get access to the controller's url variable so that the UI will reflect the changes? Simply referring to a global variable in the controller does not work, like:

$scope.url = url;


Use $apply.

From the Docs:


$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

-- AngularJS $rootScope API Reference -- $apply


AngularJS functionality should be added to webview tags by using an AngularJS directive.


<div ng-controller="MainController">
    <webview current-src="url" id="foo" 
             style="width:640px; height:480px">

    <p>Current url = {{url}}</p>


app.directive("webview",function() {
    return {
        restrict: "E",
        link: function(scope,elem,attrs) {
            var webview=elem[0];
            elem.on("loadcommit", function(e) {
                $scope.$apply(attrs.currentSrc +'='+ webview.src);

The example directive adds a loadcommit listener that sets the scope variable defined by the current-src attribute to the value of src property of the webview tag.