如何在指令中显示对象/属性?

时间:2015-12-15 06:43:41

标签: javascript angularjs

这是我显示输入字段的指令:

JS:

 .directive('isField', function () {
    return {
        restrict: 'EA',
        template: '<div class="form-group">' +
      '<label class="col-sm-2 control-label">{{prop}}</label>' +
      '<div class="col-sm-10">' +
        '<label ng-if="obj.prop" class="control-label" style="font-weight:normal;">Yes</label>' +
        '<label ng-if="!obj.prop" class="control-label" style="font-weight:normal;">No</label>' +
      '</div>' +
    '</div>',
        scope: {
          obj: "@obj",
          prop: "@prop",
        },
        controller: function(){
        },
        link: function(scope,elem,attr,ctrl){
        }
    };
})

HTML:

<is-field obj="pano" prop="isOutRoom" class="ng-isolate-scope">
  <div class="form-group">
    <label class="col-sm-2 control-label ng-binding">isOutRoom</label>
    <div class="col-sm-10">
      <!-- ngIf: obj.prop -->
      <!-- ngIf: !obj.prop -->
      <label ng-if="!obj.prop" class="control-label ng-scope" style="font-weight:normal;">No</label>
      <!-- end ngIf: !obj.prop -->
    </div>
  </div>
</is-field>

obj.prop未被评估,即使Noobj.prop,该指令也会显示true

示例JSON:

pano:
{
  "objectId": "566f915b00b0814d65fa12e0",
  "isVirtualRoom": true,
}

我是否对指令的scope:部分做错了?

1 个答案:

答案 0 :(得分:1)

我认为错误出现在您的模板中,并且恰好在ng-if中,您的模板应该像

 .directive('isField', function () {
    return {
    restrict: 'EA',
    template: '<div class="form-group">' +
  '<label class="col-sm-2 control-label">{{prop}}</label>' +
  '<div class="col-sm-10">' +
    '<label ng-if="prop" class="control-label" style="font-weight:normal;">Yes</label>' +
    '<label ng-if="!prop" class="control-label" style="font-weight:normal;">No</label>' +
  '</div>' +
'</div>',
    scope: {
      obj: "@obj",
      prop: "@prop",
    },
    controller: function($scope){

    },
    link: function(scope,elem,attr,ctrl){
    }
};

})

这是worked demo