Angularjs - 无法捕捉$watch事件



我试图实现这个指令到我的代码没有太多的成功。angular-material-fileinput .

我按照github页面的说明,我添加了"lfNgMdFileInput"到我的模块依赖项,在html中添加了html标签,除了一件事之外,一切都很好。

我应该根据文档捕获字段中输入的数据的方式是通过使用$scope.$watch('lfFilesName',function(old,new){...})

数据被指令处理得很好,所有的东西都被保存在指令的$scope中,没有问题,但是$watch事件永远不会被触发,除非它被初始化。

请让我知道,如果有什么我应该添加。代码本身是这样的:

// the piece of html
<lf-ng-md-file-input lf-files="files02" lf-api="api02" multiple></lf-ng-md-file-input>
// the piece of js; PS: While the selected files appear on the directive scope, they don't appear in the scope of my controller, 
//  witch i guess is normal but it would still have to catch the watch event, right?
$scope.$watch('files02.length',function(newVal,oldVal){
  console.log($scope.files02);
});

Edit1:(代码段)

<body  ng-controller="HomeCtrl">
<div ui-view layout="row" ng-style="checkHeightReq()">
    <md-tabs md-selected="selectedIndex"  md-dynamic-height md-stretch-tabs="always" flex="100" md-border-bottom="">
        <md-tab label="{{lang.uploadDocuments}}" ng-disabled="tabsDisabled.tab4">
              <div ng-include="'partials/tabUploadDocuments.html'" ng-controller="UploadDocCtrl"></div>
        </md-tab>
    </md-tabs>
</div>
</body>

泛音/tabUploadDocuments.html:

  <lf-ng-md-file-input lf-files="files01"></lf-ng-md-file-input>
  <lf-ng-md-file-input lf-files="files02"></lf-ng-md-file-input>

UploadDocCtrl:

angular.module('demo').controller('UploadDocCtrl', UploadDocuments);

UploadDocuments.$inject = ['$scope','LangVars','$mdMedia', '$mdToast'];
function UploadDocuments($scope, LangVars,$mdMedia, $mdToast) {
//unrelated stuff
 $scope.$watch('files02',function(newVal,oldVal){
                     console.log($scope.files02);
                 },true);   
 $scope.$watch('files01',function(newVal,oldVal){
                      console.log($scope.files02);
                  });
//unrelated stuff
}

Watch将对Model属性起作用。你可以修改你的代码,只使用'files02'(即没有长度)。

$scope.$watch('files02',function(newVal,oldVal){
                 console.log($scope.files02);
     });

我不确定这是否会解决你的问题,但仍然,看起来Angular并没有捕捉到作用域的变化,但是对象在你的代码中发生了变化。一个可能的原因是,你应用watch的对象可能会改变到Angular的作用域之外(例如……)Jquery模式等)

所以如果这是问题,那么尝试使用$apply

下面是代码片段

//place this just after the line when you are changing $scope.file02
$scope.$apply(function() {
   $scope.file02;
});

那么angular会在$watch block

中捕获它

希望能有所帮助


UPDATE:

$timeout(function(){
     $scope.$apply(function() {
       $scope.file02;
     });
});

最新更新