2014-03-30 41 views
0

需要角度上的一些幫助。 我有一個指導和我想要得到的鏈接功能控制器:AngularJS - 指令無法獲取控制器數據

link : function (scope, element, attr, ctrl) { 
//DO Something 
} 

顯然這是一件容易的事,如果我中預定義的「NG-模式」喜歡這裏它的工作:

<numric ng-model="data.mytext" /> 

,但我想用numric作爲屬性,並從它那裏得到的模型:

<div numric ="data.mytext" ></div> 

,現在當我去鏈接功能ctrl 一片空白。 我的代碼:

<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>Angular JS demo</title> 
    <script src="http://code.jquery.com/jquery-1.10.2.js"></script> 

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script> 
</head> 
<body ng-app="myApp"> 
<div ng-controller="firsttimeCtrl"> 
    <div numric="data.mytext" /> 
</div> 

</body> 
<script type="text/javascript"> 

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

myapp.controller('firsttimeCtrl',function ($scope) { 
     //$scope.data=Data; 

    }); 


myapp.directive('numric', function() { 
    return {  
    require: '?ngModel', 
    replace: true, 

    link:function (scope, element, attr, ctrl) { 

     function numricAddCommas(text){ 
     var str = text.replace(/[^0-9]/g, '');//allowing only numbers 
     var parts = (str + "").split("."), 
      main = parts[0], 
      len = main.length, 
      output = "", 
      i = len - 1; 

     while(i >= 0) { 
      output = main.charAt(i) + output; 
      if ((len - i) % 3 === 0 && i > 0) { 
       output = "," + output; 
      } 
      --i; 
     } 
     // put decimal part back 
     if (parts.length > 1) { 
      output += "." + parts[1]; 
     } 
     if(output !== text) { 
      str=output; 
      ctrl.$setViewValue(output); 
      ctrl.$render(); 
     } 
     return output; 

    } 

     ctrl.$parsers.push(numricAddCommas); 
    }, 
    template:'<input type="text" />' 


    }; 
}); 
</script> 
</html> 

有辦法知道我使用模板是在什麼控制器?或者有另一種方式? 謝謝。

+0

[門禁控制器的可能重複範圍從指令](http://stackoverflow.com/questions/19385543/access-controller-scope-from-directive) – Conqueror

回答

1

你的指令應申報範圍:

.directive("...",function(....){ 
return { 
scope:{ 
input:"=", 
}, 
link:function(scope,element,attrs){ 
//access the input as scope.input 
} 

}; 
}); 

而且使用它像:

<div directive-name input="var_name_on_scope"></div> 

你也可能需要閱讀這個問題: What is the difference between '@' and '=' in directive scope in AngularJS?

+0

這不是真的回答我的問題,但無論如何感謝。 – knightsb

相關問題