我做了一个处理文件上传的指令,它在上传文件时有效,但在预加载数据时效果不好,因为模型上的手表没有给我预期的结果。
而那些areis代码的相关部分:
http://codepen.io/sergio0983/pen/EyLwaQ?editors=1011
的一部分,是造成我头疼的是这一个:
<div ng-app = 'app' ng-controller = 'customCtrl'>
<file ng-model = 'doc' placeholder = 'modelEmpty' required></file>
<file ng-model = 'existingDoc' placeholder = 'modelNotEmpty' ng-required></file>
<div>
JS
app.controller("customCtrl", function($scope){
$scope.existingDoc = "filename.jpg"
})
app.directive("file", function($parse){
return{
restrict:"E",
require:"?ngModel",
scope:{
ngModel:"="
},
transclude:true,
.....
link:....
scope.$watch(attrs.ngModel, function(newVal, oldVal){
console.debug(newVal, oldVal);
});
}
});
这个w里面atch,我想在模型设置一个值时进行初始化,但对于newVal和oldVal,我总是会得到“undefined”,“undefined”。可能我错过了一些基本的东西,但是找不到任何东西。
此外,调用$ setViewValue甚至不会触发手表:maybeI误解了某些内容,但我认为$ setViewValue更改了模型值,所以我期望它触发$ watch。
有人能解释我应该怎么做所有东西的工作?我明显错过了一些东西。
如果你想绑定到'ngModel'(及其所有的格式化器/校验器/等等),你必须在'link'函数中使用'controllers'(第四个位置我相信)参数(假设你使用'link'函数)并访问链接函数的['ngModelController'](https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)参数。如果你只是想来回传递数据,你可以使用'='并做一个手表。你应该只需要看'ngModel'这个字符串,不过不是'attrs.ngModel'。 –
这样的事情? CTRL $ setViewValue(scope.file)。我这样做,但它不会触发$ watch – sergio0983
张贴部分“看字符串”作为答案... ^^ – sergio0983