首页 > 关于 angular 几个问题

关于 angular 几个问题

现有 angularjs 问题俩枚

一.
通过 $http 加载了一篇文章,该文章有标题, 现想实现文章加载后将文章标题替换掉浏览器标题. html 结构如下

<!doctype html>
<html data-ng-app="app">
<head data-ng-controller="head">
 <meta charset="utf-8"/>
 <titlte data-ng-bind="title||'Document'"></title>
</head>
<body>
 <div data-ng-controller="main">
  <button data-ng-click="getPost()">GET POST</button>
  <div data-ng-module="post">
   <h2 data-ng-bind="post.title"></h2>
   <article data-ng-bind="post.content"></article>
  </div>
 </div>
</body>
</html>

也就是 post 加载后浏览器标题和 post.title 显示一样.
已搜索过跨域通信的解决方案, 并且看到了 这里(AngularJS控制器controller如何通信?) , 这三种方法, 前俩种并部适合我当前这个结构, 因此使用第三种方式, 并且也是实现了同步, 但是致命的是需要通过一个触发(点击 等)才能够同步, so 其实直白了就是想问问怎么能够自动同步 而不是通过触发来同步.

二.
$scope 回调,
还拿这个加载文章来说, 比如加载的文章中有 pre 标签包裹的代码快, 在加载后, 要通过其他库来实现高亮, so 需要在数据绑定并且渲染完毕后来执行高亮操作. 但是并没有搜到什么解决方案.
自己也写了些, 俩中方案
第一种:
数据绑定后以后递归查询当前页面的所有 pre 标签, 找到后或者限定次数后 高亮 结束.
第二种:
window.setTimeout(function(){}, 1000);
俩中结果了, 第一种是不行的. 无论递归多少次都无法找到 pre 标签
第二种可行, 不过感觉这并不是一个好的解决方案


在渲染文章的模板里面比如标题那个元素上加一个 class wtitle, 就会把当前页面的title改成文章的标题.
在微信里面也可以做到~

这个wtitle的作用, 就是把element.text()的内容作为document.title来设置. 使用iframe的作用是为了使得在app的webview中也能够生效

javascriptapp.directive('wtitle', [
  '$timeout',
  '$document',
  function($timeout, $document){
    return {
      restrict: 'AC',
      link: function($scope, $element, $attrs){
        var watch = $scope.$watch(function(){
          return $element.text().replace(/(^\s*)|(\s*$)/g, '');
        }, function(title){
          // 空标题不显示
          if(/^\s*$/.test(title)){
            return;
          }
          $document[0].title = title;
          var $body = angular.element($document[0].body);
          var $iframe = angular.element('

<iframe style="visibility:hidden;" src="/path/to/iframe.png"></iframe>

');
          $iframe.on('load', function(){
            $timeout(function(){
              $iframe.off('load').remove();
            }, 5);
          });
          $body.append($iframe);
        });

        $scope.$on('$destroy', watch);
      }
    };
  }
]);

没太看明白你说的跨域通信?难不成是controller之间通信? 还有 触发?

1、 直接写 ng-bind 就行 不用data-* 这样
2、 <title> 所在的controller是和 main这个控制器平级的。你可以在他们之外加一个父控制器,然后mainController.$scope.$parent.title = post.title, 或者直接用$rootScope (不怎么推荐)。也可以通过$emit/$broadcast/$on 这样来做 不过没什么必要了。
然后:

<title ng-bind="$parent.title||'Default Title'"></title>

3、 以 angular highlight为关键字可以在github搜到一些不错的高亮插件。 bower install 之
4、 不要用window.setTimeout, 用angular提供的 $timeout() 它会返回一个promise。
5、 其实对于第二个问题更好的方法是使用 $resource.get().$promise.then(); // 或者 $http服务,确保远端数据加载完成后才执行。

【热门文章】
【热门文章】