最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs directive changing ng-model - Stack Overflow

programmeradmin1浏览0评论

I'm making a directive that mimics a <select>, but allows me more styling, but couldn't find any information on how to implement it using ng-model. Here's the directive:

.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
        }
}])

How can I set ng-model from the click event on the <li> ?

I'm making a directive that mimics a <select>, but allows me more styling, but couldn't find any information on how to implement it using ng-model. Here's the directive:

.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
        }
}])

How can I set ng-model from the click event on the <li> ?

Share Improve this question asked Jan 26, 2014 at 12:04 Kristiyan KostadinovKristiyan Kostadinov 3,7124 gold badges32 silver badges52 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Try 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
        }
}])

Template:

<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 (click on an item to see output)

发布评论

评论列表(0)

  1. 暂无评论