简体   繁体   English

AngularJS自定义指令如何访问对象值?

[英]AngularJS Custom directive How to access object value?

Here is my html code where i am calling directive 这是我正在调用指令的html代码

 <div  ng-repeat="feat in templateAttributes track by $index">
                <md-input-container flex="50"> 
                   <feat-directive feat="{{feat}}" />

                </md-input-container>

 </div> 

and below is custom directive code 以下是自定义指令代码

sureApp.directive('featDirective', function () {
 alert("Hariom");
    return {

    restrict: 'E',
    template: '<span style="padding-right:20px"><label value="{{feat.Name}}">{{feat.Name}}</label></span>',
    link: function(scope, element, feat){

        if(feat.DataType === 'Boolean'){
            element.append('<input type="text" id="{{feat.Name}}" value="{{feat.Value}}" ng-model="feat.Value" />');
        }
        else if(feat.AllowedValues && feat.AllowedValues.length > 0){
            element.append('<select ng-model="feat.Value" ng-options="x for x in feat.AllowedValues.split(\',\')"></select>');
        }

        else if(feat.DataType == 'Integer'){
            element.append('<input type="text" id="{{feat.Name}}" value="{{feat.Value}}" ng-model="feat.Value" />');
        }
        else if(feat.DataType == 'String'){
            element.append('<input type="text" id="{{attr.feat.Name}}" value="{{attr.feat.Value}}" ng-model="attr.feat.Value" ng-minlength="attr.feat.MinLength" ng-maxlength="attr.feat.MaxLength" />');
        }
        else if(feat.DataType == 'IpAddress'){
            element.append('<input type="text" id="{{feat.Name}}" value="{{feat.Value}}" ng-model="feat.Value" />');
        }

  }
  };                

});

But when i am trying to get the value of feat.DataType i am getting undefined while I am getting below values when debugging the code. 但是,当我尝试获取feat.DataType值时,我在调试代码时获得低于值的同时变得undefined

$attr
:
Object
feat
:
"{"Name":"DisplayName","DataType":"String","Description":"Display Name","Mandatory":true,"Editable":true,"Extension":false,"MinLength":3,"MaxLength":100,"AllowedValues":"","Value":""}"
__proto__
:
Object

Then i change code little bit like this 然后我像这样更改代码

  link: function(scope, element, attr) 

and tried used JSON parser 并尝试使用过的JSON解析器

var feat1 = JSON.parse(attr.feat); 

After this change below code showing {{feat.Value}} in inputbox 进行此更改之后,下面的代码在输入{{feat.Value}}显示{{feat.Value}}

<input type="text" id="{{feat.Name}}" value="{{feat.Value}}" ng-model="feat.Value" />

AngularJS directive creates it's own scope , you can access parent scope using scope isolation AngularJS指令创建自己的scope ,您可以使用scope isolation访问parent scope

AngularJS docs for directive AngularJS指令文档

you can add scope property in return 您可以添加scope属性作为回报

return {
 restrict: 'E',
 scope: {
    feat: '=feat'
 }
 ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM