簡體   English   中英

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

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

我有一個指令如下:

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);
            });
    }
}

編輯 ,這是控制器:

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);
   }

}

這是查看文件

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

附加信息,提交表單時調用regService()方法

當我調試$ scope.files時,可以在“控制台”選項卡中找到它。 但在我的控制器中,它是未定義的

那么如何在指令和控制器之間進行同步

現在正在工作。 問題是由於我使用了2個嵌套指令造成的:)謝謝大家

我將在指令定義中使用scopebindToController屬性,如該博客的以下代碼片段所示

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

它也需要使用controllerAs語法,但是無論如何都應該使用它,因為它比在各處傳遞$ scope和處理原型繼承要清晰得多。 這在John Papa的AngularJS樣式指南中推薦

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM