AngularJS如何动态添加HTML并绑定到控制器

And*_*ndy 58 javascript angularjs

我刚开始使用angularJS并且正在努力找出适合我正在尝试的架构.我有一个单页应用程序,但URL始终保持不变 ; 我不希望用户能够导航到root之外的任何路由.在我的应用程序中,有一个主要div需要托管不同的视图.访问新视图时,我希望它接管主div中的显示.以这种方式加载的视图可以丢弃或隐藏在DOM中 - 我很想知道每个视图的工作原理.

我想出了一个粗略的工作示例,说明我正在尝试做什么. 请参阅此Plunk中的工作示例. 基本上我想动态地将HTML加载到DOM中,并让标准的angularJS控制器能够挂钩到新的HTML中.有没有更好/更简单的方法来做到这一点,而不是使用我在这里的自定义指令并使用$ compile()来连接到角度?也许有点像路由器,但是不需要URL有变化才能运行?

这是我到目前为止使用的特殊指令(取自另一个SO帖子):

// Stolen from: http://stackoverflow.com/questions/18157305/angularjs-compiling-dynamic-html-strings-from-database
myApp.directive('dynamic', function ($compile) {
  return {
    replace: true,
    link: function (scope, ele, attrs) {
      scope.$watch(attrs.dynamic, function(html) {
        if (!html) {
            return;
        }
        ele.html((typeof(html) === 'string') ? html : html.data);
        $compile(ele.contents())(scope);
      });
    }
  };
});
Run Code Online (Sandbox Code Playgroud)

谢谢,

安迪

jes*_*vin 64

我会使用内置ngInclude指令.在下面的示例中,您甚至不需要编写任何javascript.模板可以轻松地存在于远程URL中.

这是一个有效的演示:http://plnkr.co/edit/5ImqWj65YllaCYD5kX5E?p = preview

<p>Select page content template via dropdown</p>
<select ng-model="template">
    <option value="page1">Page 1</option>
    <option value="page2">Page 2</option>
</select>

<p>Set page content template via button click</p>
<button ng-click="template='page2'">Show Page 2 Content</button>

<ng-include src="template"></ng-include>

<script type="text/ng-template" id="page1">
    <h1 style="color: blue;">This is the page 1 content</h1>
</script>

<script type="text/ng-template" id="page2">
    <h1 style="color:green;">This is the page 2 content</h1>
</script>
Run Code Online (Sandbox Code Playgroud)

  • 查看有关该主题的官方视频-http://campus.codeschool.com/courses/shaping-up-with-angular-js/level/2/section/2/video/1 (2认同)

小智 17

还有另一种方式

  1. 第1步:创建一个sample.html文件
  2. 第2步:使用一些id = loadhtml创建一个div标签例如: <div id="loadhtml"></div>
  3. 第3步:在任何控制器中

        var htmlcontent = $('#loadhtml ');
        htmlcontent.load('/Pages/Common/contact.html')
        $compile(htmlcontent.contents())($scope);
    
    Run Code Online (Sandbox Code Playgroud)

这将在当前页面中加载html页面

  • 应该是AngularJs,而不是jQuery (7认同)

RPD*_*ies 12

对于那些像我一样,没有可能使用角度指令并被"卡住"在角度范围之外的人,这里可能会对你有所帮助.

在网上和角度doc上搜索了几个小时之后,我创建了一个编译HTML的类,将它放在一个目标中,然后将它绑定到一个范围($rootScope如果$scope该元素没有)

/**
 * AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
 */
var AngularHelper = (function () {
    var AngularHelper = function () { };

    /**
     * ApplicationName : Default application name for the helper
     */
    var defaultApplicationName = "myApplicationName";

    /**
     * Compile : Compile html with the rootScope of an application
     *  and replace the content of a target element with the compiled html
     * @$targetDom : The dom in which the compiled html should be placed
     * @htmlToCompile : The html to compile using angular
     * @applicationName : (Optionnal) The name of the application (use the default one if empty)
     */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);

        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
            //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
    }

    return AngularHelper;
})();
Run Code Online (Sandbox Code Playgroud)

它涵盖了我的所有案例,但如果您发现我应该添加的内容,请随时评论或编辑.

希望它会有所帮助.