【问题标题】:angular js dom manipulation with directives带有指令的角度js dom操作
【发布时间】:2013-08-12 02:24:58
【问题描述】:

我正在尝试使用角度指令来动态替换页面 portlet 的 html 部分。

html portlet 嵌入了 2 个部分。顶部的标题是从不同的后端服务获取的

<div class="headerdiv">
<h3 class='headerclass'> <a href="">Object Heading</a> </h3>
</div>

内容被加载到不同的部分

<div id="objectDiv" ng-controller="ObjectCtrl">
   <div ng-show="object.title" mydirective><b>{{object.title}} </b></div>

   <div element-trigger><b>{{object.name}} </b></div>
   <div element-trigger><b>{{object.description}} </b></div>

 </div>

控制器加载细节成功

添加的新指令是

  app.directive('mydirective', function(){
        return function(scope, elem, attrs){
        //obtain old header
    var oldHeader = angular.element( '.headerdiv .headerclass' );

    //get the new header

    //replace old header with new header
      }
 });

我需要使用 object.title 值动态更改 headerdiv 中的标题。请注意,新指令绑定到正在侦听 object.title div 的字段。

【问题讨论】:

    标签: css html dom angularjs angularjs-directive


    【解决方案1】:

    我不认为这是指令的正确使用,因为在大多数情况下,指令应该用于影响定义它的元素的功能。

    你可以尝试在ObjectCtrl中定义一个关于title属性的watch,然后广播消息

    $scope.$watch('object.title',function(newValue) {
       $rootScope.$broadcast('titleChanged',newValue);  //You can pass any object too
    });
    

    如果您的标头包含在控制器中,则捕获该事件

    $scope.$on('titleChanged',function(args) {
        //Code to handle the title update
    });
    

    标题的html应该有标题的绑定表达式

    <div class="headerdiv">
    <h3 class='headerclass'> <a href="">{{title}}</a> </h3>
    </div>
    

    注意:我不确定 html 的结构,但如果 ObjectCtrl 中的标头和内容使用相同的\共享模型(对象),则不需要这一切.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多