2015-08-26 50 views
0

内部控制器我想有多个模板的指令,因为在this SOAngularJS - 与NG-包括绕过指令

当使用一个指令编译为this jsfiddle 的的NG-包括使用编译外部控制器和 和内部控制器不可用的模板的范围

例如

function someDirective(){ 
return { 
scope:{ 
    ... 
}, 

compile: function(element, attrs) { 
    var type = "extended"; //default 
    if(typeof attrs.type !== 'undefined') 
    type = attrs.type; 
    element.append('<div ng-include="\'myproj/views/templates/group/groups-' + type + '.html\'"></div>'); 
}, 
//templateUrl: 'myproj/views/templates/group/groups-sideMenu.html', 
controller:function($scope, $attrs, $rootScope, UtilsSrvc){ 
    // ... the template won't use this controller 
} 
} 
} 

如何解决这一问题问题?

编辑

经过一番headbang东西有更清晰的 In this fiddle(亚历山德罗Cifani)剧本的作品无论是对角1.0,角1.1和角1.2

的问题试图范围隔离时启动: this fiddle只适用于Angular < = 1.1,而Angular> = 1.2不起作用

当一个空的'templateUrl'是adde时d如图this fiddle:它开始是兼容所有版本

???????????????

回答

1

我会用不同的方法:

1)同比可以使用$compile服务

2)应避免在有利于定制指令的使用ng-include

下面的例子我在说什么:

(function() { 
    'use strict'; 

    angular.module('myApp', []) 

    .directive('user', 
    function user($compile, $window) { 
     return { 
     scope: { 
      role: '@', 
      name: '@' 
     }, 
     restrict: 'EA', 

     link: function link(scope, elem) { 

      var roles = { 
      SUPERADMIN: '<button ng-click="doSomething()" class="btn">Do something</button>', 
      STUDENT: '<div class="alert alert-success">You are a student</div>', 
      OTHER: '<div>Guest users have no options</div>' 
      }; 

      // Create HTML elements in according with the role (SUPERADMIN, STUDENT, OTHER) 
      var role = roles[scope.role] || roles.OTHER; 
      var html = '<div><h2>' + scope.name + '</h2>' + role + '</div>'; 

      // Step 1: parse HTML into DOM element 
      var template = angular.element(html); 
      //console.log (html); 

      // Step 2: compile the template 
      var linkFn = $compile(template); 
      //console.log (linkFn); 

      // Step 3: link the compiled template with the scope. 
      var element = linkFn(scope); 
      console.log (element[0]); 

      // Step 4: Append to DOM (optional) 
      elem.append(element); 

      scope.doSomething = function doSomething() { 
      $window.alert('doSomething'); 
      }; 

     } 
     }; 
    } 
); 

})(); 

用法:

<user name="fabio" role="SUPERADMIN"></user> 
<user name="paolo" role="STUDENT"></user> 
<user name="marco"></user> 

注:在前面的例子中,你可以代替我的“超级管理员”,“学生”和“其他“模板与您自己的自定义指令,即:,

和这里一个JSBin:https://jsbin.com/mumahobuwu/edit?html,js,output