代码之家  ›  专栏  ›  技术社区  ›  marlar

Chrome应用程序和Android“webview”标签的AngularJS指令

  •  1
  • marlar  · 技术社区  · 8 年前

    例如,我有一个webview,它的当前地址由loadCommit监控。下面是简化的代码:

    HTML片段:

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

    控制器:

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

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

    如何访问控制器的url变量,以便UI反映更改?简单地在控制器中引用全局变量是行不通的,例如:

    $scope.url = url;
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   georgeawg    8 年前

    使用 $apply .

    从文档中:

    $apply([exp]);

    $apply() 用于从角度框架外部以角度执行表达式。(例如,通过浏览器DOM事件、setTimeout、XHR或第三方库)。因为我们正在调用角度框架,所以需要执行适当的范围生命周期 exception handling , executing watches .

    -- AngularJS $rootScope API Reference -- $apply


    使现代化

    webview 标记。

    HTML格式

    <div ng-controller="MainController">
        <webview current-src="url" id="foo" 
                 src="http://stackoverflow.com/"
                 style="width:640px; height:480px">
        </webview>
    
        <p>Current url = {{url}}</p>
    </div>
    

    指令

    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);
                });
            }
        };
    });
    

    示例指令添加了 loadcommit 设置由 current-src 属性的值 src 的属性 网络视图 标签