3

我需要访问指令创建的模型,同时我需要获取指令中的attrs。如何访问隔离范围的指令attrs?

JS:

module.directive('createControl', function($compile, $timeout){ 
return {    
    scope: {   
    name: '=Name' // Dynamically created ng-model in the directive element 
    }, 
    link: function(scope, element, attrs){ 
    attrs.$observe('createControl', function(){ 
     attrs.createControl //is empty if scope is an object, otherwise it is passed from html attribute 
    } 
    } 

HTML:

<div class="control-group" ng-repeat="x in selectedControls"> 
    <div create-control="{{ x }}"></div> 
</div> 

如果scope被定义为一个对象,attrs是空的,否则它是从HTML传递的值。

这种行为的原因是什么?如何获得通过attrs和模型?

+1

“= Name”语法要求您的HTML具有“Name”属性。例如,'

' – 2013-05-07 14:35:44

+0

'=在指令html中动态添加的名称属性。所以是的,这是存在的。此外,我可以得到它。 “attrs”的问题。 – I159 2013-05-07 14:50:22

+0

@ I159你可以在你说的名字是动态添加的地方包含你的指令HTML吗? – Langdon 2013-05-07 15:03:15

回答

3

问题:create-control需求父范围内评估{{x}},但通过使scope时,该指令被宣布创建一个分离范围的对象。这意味着attrs.createControl无权访问x。因此,它是空的。

一个解决方案:可以解决这个问题几种方式,其中最好的是你的指令,通过配置一个属性接受scope.createControl到它的分离范围。

工作小提琴:http://jsfiddle.net/pvtpenguin/tABt6/

myApp.directive('createControl', function ($compile, $timeout) { 
    return { 
     scope: { 
      name: '@', // Dynamically created ng-model in the directive element 
      createControl: '@' 
     }, 
     link: function (scope, element, attrs) { 
      scope.$watch('createControl', function() { 
       // the following two statements are equivalent 
       console.log(attrs.createControl); 
       console.log(scope.createControl); 
      }) 
     } 
    } 
}) 
0

我需要有访问模式的指令创建

module.directive('createControl', function($compile, $timeout){ 

    return {    
     ... 
     require:'ngModel', 
     link:function(scope, element, attrs, ngMdlCntrl){ 
      //You have the access to the model of your directive here thr. ngMdlCntrl 
     } 
     ... 
    }}) 

的要求ng-model是模型在你的动态设置。

1

同意马特,但只有在设置了attrs时,以下两个语句才是等同的。

console.log(attrs.createControl);

console.log(scope.createControl);

否则,attrs.createControl将不确定,但scope.createControl将具有定义的功能。