2014-01-26 43 views
2

我正在做一个模拟<select>的指令,但允许我更多的样式,但找不到任何有关如何使用ng模型实现它的信息。这里的指令:Angularjs指令改变ng模型

.directive('customSelect', [function() { 
     return { 
      restrict:'EA', 
      require: "ngModel", 
      scope:{ 
       choices:"=", 
       selected:"=" 
      }, 
      template:'\ 
       <div class="custom-select">\ 
        <div class="label">{{ selected }}</div>\ 
        <ul>\ 
         <li data-ng-repeat="choice in choices" data-ng-click="ngModel = choice">{{ choice }}</li>\ 
        </ul>\ 
       </div>', 
      replace:true 
     } 
}]) 

如何设置NG-模型从上<li> click事件?

回答

5

尝试ngModel.$setViewValue

app.directive('customSelect', [function() { 
     return { 
      restrict:'EA', 
      require: "?ngModel", 
      scope:{ 
       choices:"=", 
       selected:"@" 
      }, 
      link:function(scope,element, attrs,ngModel){ 
       scope.select = function (choice){ 
       ngModel.$setViewValue(choice); 
       } 
      }, 
      templateUrl:"template.html", 
      replace:true 
     } 
}]) 

模板:

<div class="custom-select"> 
    <div class="label">{{ selected }}</div> 
    <ul> 
    <li data-ng-repeat="choice in choices" data-ng-click="select(choice)">{{ choice }}</li> 
    </ul> 
</div> 

DEMO(点击项目查看输出)

+2

演示是不完整的。 – StarsSky

+1

@StarsSky:啊,保存时出现问题,我再次创建演示 –

+2

@StarsSky:更新了演示网址。感谢您指出 –