我正在尝试创建一个具有选择(下拉菜单)的指令,当您选择其中一个选项时,它将改为输入。
下拉列表的值为 1-12,其中一个值为“更多...”,当用户选择“更多...”时,选择应更改为输入。
问题是变化永远不会发生。
我在 plunker 中有我的代码供人们玩:http ://plnkr.co/edit/3SyFIYULDHMKgkJmtPtP?p=preview
var app = angular.module( 'myApp', [] ); // create app
app.controller( 'myCtrl', [ '$scope', function ( $scope ){ // simple controller
$scope.value = '0';
$scope.$watch('value', function(newValue, oldValue){
console.log('watch fired in controller', newValue); // write the new value on change
});
}]);
app.directive('selectSwitch', function () { // the directive
return {
restrict: 'E',
template: '<div>'+ // template should know to switch between input and select
'<input ng-model="myModel" ng-if="showInput" />'+
'<select ng-model="myModel" ng-if="!showInput">'+
'<option ng-repeat="value in selectSwitchValues" value="{{value}}">{{value}}<option>'+
'<select>'+
'<div>',
scope: {
myModel: '=', // tie it to my model
},
link: function (scope, elem, attrs) {
scope.selectSwitchValues = ['1','2','3','4','5','6','7','8','9','10','11','12','more...']; // values for select
scope.showInput = false;
scope.$watch('myModel', function(newValue, oldValue){ // watch for changes in directive
console.log('watch fired in directive');
if(scope.myModel === "more..."){
console.log("more");
scope.showInput = true;
}
else {
console.log(scope.myModel);
}
});
}
};
});
我也用 ng-switch 尝试过,但也没有运气:
template: '<div ng-switch on="showInput">'+
'<input ng-model="myModel" ng-switch-when="showInput">'+
'<select ng-model="myModel" ng-switch-default>'+
'<option ng-repeat="value in selectSwitchValues" value="{{value}}">{{value}}<option>'+
'<select>'+
'<div>',