angular 1.4指令切换视图

问题描述 投票:1回答:1

我想根据切换属性显示两个不同的输入。

不,我有问题,我应该在我的指令中定义输入的每个属性/属性,但绑定不起作用。

指示:

angular.module('directive')
.directive('inputBlock', function () {
    return {
        restrict: 'AEC',
        replace: true,
        scope: {
            model: '=',
            modernStyle:'=',
            name:'=',
            type:'=',
            label:'='
        },
        link: function (scope, elem, attrs, ctrl) {},
        templateUrl: 'views/templates/inputBlockTemplate.html'
    };
});

模板:

<div>
<div ng-if="!modernStyle">
<label>{{label}}</label>
<input ng-model="model" name="{{name}}" type="{{type}}"/>
</div>
 <md-input-container ng-if="modernStyle">
  <label>{{label}}</label>
  <input ng-model="model" name="{{name}}" type="    {{type}}"/>
</md-input-container>
</div>

用法:

 <input-block model="name" label="'firstname'" modern-style="true" name="'firstname'" type="'text'">
  </input-block>

是否有可能在指令中执行类似切换的操作?此外,是否可以将绑定重定向到指令?

angularjs angularjs-directive
1个回答
0
投票

ng-if创建了一个新的子范围,尝试通过ng-show/ng-hide进行更改

Understanding Scopes

其他考虑:

  • 当你在你的指令中使用name,label和type作为文本时,它不是必须绑定的,我建议使用@而不是=,或直接从attrs link参数访问它。
  • scope.model可以设置为ngModel以使用默认的angular指令。

使用Javascript:

angular.module("directive").directive("inputBlock", function () {
    return {
        restrict: "AEC",
        replace: true,
        scope: {    
            ngModel: "=",
            modernStyle:"@",
            //name:"@",
            //type:"@",
            //label:"@"
        },
    link: function (scope, elem, attrs, ctrl) {
         scope.type=attrs.type;
         scope.name=attrs.name;
         scope.label=attrs.label;
     },
    templateUrl: "views/templates/inputBlockTemplate.html"
    };
});

模板:

<div>
<div ng-show="!scope.modernStyle">
<label>{{scope.label}}</label>
<input ng-model="scope.model" name="{{scope.name}}" type="{{scope.type}}"/>
</div>
 <md-input-container ng-show="scope.modernStyle">
  <label>{{scope.label}}</label>
  <input ng-model="scope.model" name="{{scope.name}}" type={{scope.type}}"/>
</md-input-container>
</div>

用法:

<input-block ng-model="name" label="firstname" modern-style="true" name="firstname" type="text">
  </input-block>
© www.soinside.com 2019 - 2024. All rights reserved.