如何构建类似于 ng-model 的自定义指令?

How to build Custom directive similar to ng-model?

我想构建一个与 ng-model 工作方式相同的指令 directive.I 使用 $watch 尝试了它,但无法构建。任何人都可以帮助我吗?提前谢谢你。

试试这个:

JS:

app.directive('simpleMOdel', function (){
return function (scope,elem,attrs) {
var modelGetter = $parse(attrs.simpleMOdel);
var modelsetter =modelGetter.assign;
scope.$watch(modelGetter,function(newVal,oldVal){
elem.val(newVal);
});
//DOM model updates
elem.bind('input',function () {
modelSetter(scope,elem.val())
})
}
})

HTML:

<input  simple-model='name'>
<span simple-model-bind="name"></span>