Angularjs指令改变ng模型

Jon*_*now 2 javascript angularjs angularjs-directive

我正在做一个模仿a的指令<select>,但允许我更多的样式,但是找不到任何关于如何使用ng-model实现它的信息.这是指令:

.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
        }
}])
Run Code Online (Sandbox Code Playgroud)

如何从点击事件中设置ng-model <li>

Kha*_* TO 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
        }
}])
Run Code Online (Sandbox Code Playgroud)

模板:

<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>
Run Code Online (Sandbox Code Playgroud)

DEMO(点击一个项目查看输出)

  • 演示不完整. (2认同)
  • @StarsSky:更新了演示网址.谢谢你指出 (2认同)