0

need some help on angular. i have a directive and i want to get the controller on the link function:

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

apparently it is an easy task, and it does work if i predefined the "ng-model" like here :

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

but i want to use numric as an attribute and to get the model from it:

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

and now when i get to the link function ctrl is null. my code:

 <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>

there is a way to know what controller i'm in by using the template? or there is another way? Thanks.

1

1 Answer 1

1

Your directive should declare a scope:

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

};
});

And use it like:

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

You might also want to read this question: What is the difference between '@' and '=' in directive scope in AngularJS?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.