0

here is the jsfiddle. HTML:

<div ng-app="app">
    <div ng-controller="ctrl">
        <div my-rd name="gender" value="male" model="gender"></div>
        <div my-rd name="gender" value="female" model="gender"></div>
        <p>Your choice is: {{gender}}</p>
    </div>
</div>

JS:

angular.module("app", [])
.directive("myRd", function(){
    return{
        restrict: "A",
        scope: {
            name: "@",
            value: "@",
            model: "="
        },
        template: "<input name='{{name}}' ng-model='model' value='{{value}}' checked type='radio' />{{value}}"
    }
})
.controller("ctrl", function($scope){

})

I created a directive which can generate a custom radio button with custom attributes. The problem is I can't set ng-model name correctly and the "checked" property doesn't work as well.
Please give me a hand, many thanks!

SPG
  • 6,109
  • 14
  • 48
  • 79
  • What do you mean by can't set ng-model name correctly ? And checked is used mainly for checkbox. – Gaurav Oct 21 '15 at 05:26
  • I guess, it should be ng-checked='{{model}}'. That sets the value to the model value, if that's what you wish to achieve. – ShivangiBilora Oct 21 '15 at 05:32
  • [Check this link](http://stackoverflow.com/questions/13014303/updating-ng-model-within-a-directive-that-uses-a-template) – Amit Nair Oct 21 '15 at 05:35
  • I have tested your code and it's working fine. ng-model also working fine. When check any radio I get Your Choice is: male, and Your Choice is:female. – Kanti Oct 21 '15 at 05:43
  • I have model: '=' in my scope, but the ng-model in directive always showed "model". If I wrote
    , the ng-model in directive should be ng-model="test". What have I done wrong?
    – SPG Oct 21 '15 at 05:47
  • Do you mean the naming of your attribute is incorrect? If so `=` means it must have the same name as the scope property. – ste2425 Oct 21 '15 at 07:02

1 Answers1

1

You use the shorthand syntax = that means the attribute name is the same as the value you want to bind to inside the directive's scope.

If the declaration is <div my-rd foo="test"> then you have to specify in your directive

model: "=foo" //It tells $compile to bind to the foo attribute.

Here in your directive you can access the value

//directive will know only the property inside scope:{'your_propery': value}    
//to access the value inside directive {{your_propery}}
scope.model //{{model}}

And in your controller you can access the value

$scope.test //{{test }}

More details

Tasnim Reza
  • 6,058
  • 3
  • 25
  • 30