【问题标题】:Angular JS - template of a directive ng -model does not work within ng -switchAngular JS - 指令 ng -model 的模板在 ng -switch 中不起作用
【发布时间】:2016-04-04 16:07:23
【问题描述】:

为了变得更加动态,我的指令决定包含用于选择要显示的模板类型的类别字段。因为它只是选择使用 switch - ng 而不是几个 html 文件的想法。 (谷歌翻译)

Plunker:http://plnkr.co/edit/fnCJj15XJN1kQvKq1OtZ?p=preview

index.html

<div ng-controller="MainCtrl">
<sg-combo 
  selected-item="selectedItem" categoria="filtro">
</sg-combo>

{{selectedItem}}

script.js

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
  $scope.selectedItem = {value: null};
  $scope.$watch('selectedItem',function(item){
  if (item != null){
    alert(item.nome); // does not display when updating
  }
 })
});

app.directive('sgCombo', function(){
function link(scope, elem, attrs){    
        scope.dados = [
            {'codigo':1, 'nome':'teste1'},
            {'codigo':2, 'nome':'teste2'},
            {'codigo':3, 'nome':'teste3'}
        ];
}

return {
        restrict: 'E',          
    scope: {            
        selectedItem: '=',            
        categoria: '@'            
    },
    link: link,
    templateUrl:"sg-combo.html"
 }
})

sg-combo.html

<div ng-switch="categoria">
 <div ng-switch-when="filtro" class="col-sm-4 control-label">
   <div class="col-sm-4 control-label">
     <label>{{label}}</label>
     <select ng-model="selectedItem.value" ng-options="item.nome for item in dados" class="form-control"></select>
   </div>
 </div>
 <div ng-switch-when="anexo" class="col-sm-4 control-label">
  <div class="col-sm-4 control-label">
    <label>{{label}}</label>
    <select ng-model="selectedItem.value" ng-options="item.nome for item in dados" class="form-control"></select>
  </div>
 </div>
</div>

【问题讨论】:

标签: angularjs angularjs-directive


【解决方案1】:

尝试使“selectedItem”成为对象的一部分。 例如:

在控制器中: $scope.options = {'selectedItem': someItem};

在模板中: ng-model="options.selectedItem"

【讨论】:

  • 我看到你编辑了代码,完全按照我在这里的建议去做。它奏效了吗?如果是这样,一个upvote会很好:)
【解决方案2】:

【讨论】:

  • 更改有问题的原始代码是个坏主意,所以我的回答可能会让某些人感到困惑。请查看original version
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 2018-06-06
相关资源
最近更新 更多