在AngularJs中查找元素并更改其内容

Find element and change its content in AngularJs

本文关键字:AngularJs 查找 元素      更新时间:2023-09-26

我想更改标题div:的默认内容

<div>
  <div>
      <div class="page-header">
        <h1><span>{{messages['default_title']}}</span></h1>
      </div>
  <div>
  <!-- other elements-->
<div>

在我的控制器中,我写道:

var titleElement = angular.element('div.page-header');
titleElement.html('<h1><span>Hello</span></h1>');

div的内容更改成功:

<div class="page-header"><h1><span>Hello</span></h1></div>

但我收到了这个错误,页面无法成功加载:

TypeError: Cannot read property 'childNodes' of undefined
    at g (https://localhost/test/js/angular/angular.min.js:47:278)
    at g (https://localhost/test/js/angular/angular.min.js:47:273)
    at g (https://localhost/test/js/angular/angular.min.js:47:273)
    at g (https://localhost/test/js/angular/angular.min.js:47:273)
    at g (https://localhost/test/js/angular/angular.min.js:47:273)
    at https://localhost/test/js/angular/angular.min.js:46:377
    at link (https://localhost/test/js/angular/angular-route.js:915:7)
    at J (https://localhost/test/js/angular/angular.min.js:54:373)
    at g (https://localhost/test/js/angular/angular.min.js:47:256)
    at https://localhost/test/js/angular/angular.min.js:46:377 <div ng-view="" class="ng-scope">

而不是操纵页眉。

尝试更新控制器中的变量

$scope.messages['default_title'] = "Hello";

angular.element接受HTML字符串或JS元素,而不是选择器

var titleElement = angular.element(document.querySelector('.page-header'));
titleElement.html('<h1><span>Hello</span></h1>');