简体   繁体   English

如何在角度指令和控制器之间同步$ scope

[英]how to sync $scope between a directive and controller in angular

I have a directive as the following: 我有一个指令如下:

app.directive('fileInput', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function (scope, element, attrs) {
        element.bind('change', function () {
            $parse(attrs.fileInput)
            .assign(scope, element[0].files)
            scope.$apply();
        });
        scope.$watch('files', function () {
            console.log(scope.files);
        });
    },
    controller: function ($scope, $element, $attrs) {
        $element.bind('change', function () {
            $parse($attrs.fileInput)
            .assign($scope, $element[0].files)

            $scope.$apply();
        });
        $scope.$watch('files', function () {
                console.log($scope.files);
            });
    }
}

EDIT and this is controller: 编辑 ,这是控制器:

controllers.controller('RegisterCtrl', ['$scope', '$routeParams', '$location', '$http', 'Restangular', 'ServiceRepository', 
function($scope, $routeParams, $location, $http, Restangular, ServiceRepository) 
{
   $scope.regService = function () {
        $scope.error = {};
        $scope.submitted = true;

        var fd = new FormData();
        fd.append("model", angular.toJson($scope.services));

        console.log($scope.files);
   }

}

And this is view file 这是查看文件

<input type="file" id="boarding-picture_where_sleeping" class="form-control" file-input="files" multiple>

Additional info, regService() method is called when submitting the form 附加信息,提交表单时调用regService()方法

and when I debug $scope.files, it's available in console tab. 当我调试$ scope.files时,可以在“控制台”选项卡中找到它。 but in my controller, it's undefined 但在我的控制器中,它是未定义的

so how to sync it between the directive and controller Thanks 那么如何在指令和控制器之间进行同步

it's working now. 现在正在工作。 the problem was caused I used 2 nested directives :) Thanks guys 问题是由于我使用了2个嵌套指令造成的:)谢谢大家

I would use scope and bindToController attributes in the directive definition, like in the following snippet from this blog : 我将在指令定义中使用scopebindToController属性,如该博客的以下代码片段所示

app.directive('someDirective', function () {
  return {
    scope: {
      name: '='
    },
    controller: function () {
      this.name = 'Pascal';
    },
    controllerAs: 'ctrl',
    bindToController: true,
    template: '<div>{{ctrl.name}}</div>'
  };
});

It requires use of the controllerAs syntax too, but you should be using that anyway as it is much more clear than passing $scope around everywhere and dealing with prototypical inheritance. 它也需要使用controllerAs语法,但是无论如何都应该使用它,因为它比在各处传递$ scope和处理原型继承要清晰得多。 This is recommended in John Papa's AngularJS Style Guide 这在John Papa的AngularJS样式指南中推荐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM