简体   繁体   English

angularjs编译ng-controller和插值

[英]angularjs compile ng-controller and interpolation

On the docs I saw an example of compiling "something" added later. 文档上,我看到了稍后添加的“东西”编译示例。

var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
$(document.body).append($div);

angular.element(document).injector().invoke(function($compile) {
  var scope = angular.element($div).scope();
  $compile($div)(scope);
});

I've added this code on a jquery ready function, but I have two problems: 我已经在jQuery ready函数上添加了代码,但是我有两个问题:

First is an error: Argument 'MyCtrl' is not a function, got undefined . 首先是一个错误: Argument 'MyCtrl' is not a function, got undefined

The second is that I don't know how to make that content.label works! 第二个是我不知道如何使content.label起作用! I've added it to the scope but it doesn't work. 我已将其添加到scope但是它不起作用。 How should I call my controller to see working the data binding of content.label ? 我应该如何调用控制器以查看content.label的数据绑定正常工作?

MY FINAL MODIFIED CODE IS: 我最后修改的代码是:

var app = angular.module('app',[]);

    $(function(){

        app.controller('MyCtrl',function($scope){
            $scope.content = 123;
        });

        var $div = $('<div ng-controller="MyCtrl">{{content}}</div>');
        $(document.body).append($div);

        angular.element(document).injector().invoke(function($compile) {
          var scope = angular.element($div).scope();
          $compile($div)(scope);
        });

    });

UPDATE 更新

You should start a digest cycle after compiling new markup, in order to build all bindings and fire watchers. 您应在编译新的标记后开始摘要循环,以构建所有绑定和消防员。 This can be done by calling scope.$digest(); 这可以通过调用scope.$digest();来完成scope.$digest(); :

$compile($div)(scope);
scope.$digest();

The result should look like: 结果应如下所示:

var app = angular.module('app',[]);
  app.controller('MyCtrl',function($scope){
      $scope.content = 123;
  });

  angular.element(document).ready(function () {
      var $div = $('<div ng-controller="MyCtrl">{{content}}  </div>');
      $(document.body).append($div);

      angular.element(document).injector().invoke(function($compile) {
        var scope = angular.element($div).scope();
        $compile($div)(scope);
        scope.$digest();
      });

  });

http://plnkr.co/edit/dDNBxf8SowKTPgnVj0tF?p=preview http://plnkr.co/edit/dDNBxf8SowKTPgnVj0tF?p=预览

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM