Angular指令不附加数据

时间:2014-11-11 07:36:18

标签: angularjs angularjs-directive angularjs-scope

我尝试通过指令附加一些内容但从未出现在视图中。如果我记录编译范围,我可以看到对象。

angular.module('blancAppApp')
  .controller('SlugCtrl', function ($scope, WpApi, $compile, $filter, ngProgressLite) {

    // the Content to be rendered.
   $scope.maincontent = [];
   // load remote data from the server.
   function loadRemoteData() {
   // The WpApiService returns a promise.
        WpApi.getContents()
        .then(
            function( post ) {       
                applyRemoteData( post );       
            });    
    }

     // apply the remote data to the local scope.
    function applyRemoteData( newContents ) {    
        $scope.maincontent  = $compile( newContents[0].content )($scope);  
        console.log($scope.maincontent); // Object getting logged
    }     

}).directive('maincontent', function() {

    return {
            restrict: 'A',
                scope: {
                    maincontent: '=maincontent'
                },

                link: function (scope, element, attrs) {  

                       element.append( scope.maincontent  );
                    }
                };
});

标记

<div id="main-content" data-maincontent="maincontent"></div>

1 个答案:

答案 0 :(得分:1)

您需要在范围上注册观察者,因为请求是异步的:

var unregister = scope.$watch('maincontent', function(val) {
  if(!val) { return; }
  element.append( val  );
  unregister();
});