【问题标题】:Unable to manipulate DOM content of Ionic Android app无法操作 Ionic Android 应用程序的 DOM 内容
【发布时间】:2016-11-24 11:52:45
【问题描述】:
angular.module("app.categories").controller("CategoryController", t),  t.$inject = ["$scope", "$stateParams", "$state", "categoryManager"]

angular.module("app", ["ionic", ["app.home","app.products",...]);
angular.module("app").run(["$templateCache", function(t) {
t.put("app/scripts/about/about.html", '<ion- view>.....'),t.put("app/scripts/home/block.html", '<div>....')}]); //this is how the page content is loaded

我正在使用 Ionic(根目录中的“Ionic serve”)在浏览器中运行此应用程序。我无法在这样加载内容的页面上运行基本的 JavaScript。如果调用 DOMContentLoaded 超时后,元素会被拾取,但运行以下仅操作元素的 id,而不是 html 或值

  setTimeout(function(){
        document.addEventListener('DOMContentLoaded',function(){
            document.getElementById('customBox').id = 'changed'; //to test, id changes
            document.getElementById('customBox').innerHtml = '<h1> test </h1>'; //does not change anything, no errors in console
            document.getElementById('customBox').text= '<h1> test </h1>'; //does not change anything, no errors in console
            document.getElementById('customBox').html= '<h1> test </h1>'; //does not change anything, no errors in console

});

},2000);

是否有任何东西阻止对浏览器中的页面内容进行任何更改?如何为这个 Ionic Android 应用使用简单的 JavaScript 更改 DOM 内容?

【问题讨论】:

    标签: android angularjs cordova ionic-framework


    【解决方案1】:

    除非您编写了自定义指令,否则不要尝试直接操作 Angular 应用程序的 html。如果你想改变 innerHtml 在 div 上使用 ng-bind-html 并修改你的范围。

    另外,不要在 Angular 应用中使用 setTimeout,始终使用 $timeout$interval 服务。

    所以你的代码,在控制器的某个地方,应该是这样的:

    $scope.testContent = '<h1> tet </h1>';
    

    和html:

    <div id='customBox' ng-bind-html="testContent"></div>
    

    虽然您的代码不起作用的主要原因是,一旦您将 id 更改为“已更改”,所有其他 getElementById 调用将找不到 div。

    【讨论】:

    • 尝试 $timeout,关于 id 更改,这只是为了测试至少与元素更改相关的内容,即使在我删除 id 更改后也会发生同样的事情,其余的不要改变任何东西
    【解决方案2】:

    尝试像这样使用 angular.element

    angular.element( document.getElementById('customBox') ).innerHtml = '<h1> test </h1>';
    

    访问此链接了解详情https://docs.angularjs.org/api/ng/function/angular.element

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 2016-02-01
      • 2016-05-18
      • 2019-02-07
      相关资源
      最近更新 更多