Angular 服务或根函数

Angular Service or Root Function

我想重新组织我的代码,以便我可以与不同的控制器共享一个对话框页面(即每个控制器打开相同的对话框) 我的对话框应该是服务还是指令......我不确定如何让它对控制器可用并访问范围 像这样:

   app.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
    $scope.getProperties = function(){
        $scope.data=[];
        //var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
        var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
        var url = apiserv+"api.properties.test.php"+data;
        $http.jsonp(url).success(function(data){
            $scope.data=data;
        });
    };

    var vm = this;
    function stateChange(iColumn, bVisible) {
        console.log('The column', iColumn, ' has changed its status to', bVisible);
    }

    // TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
    // Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
    var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
    var url = apiserv+"api.properties.test.php"+data;
    vm.dtOptions = DTOptionsBuilder.fromSource(url)
        .withBootstrap()
        // Active Buttons extension
        .withButtons([
            //'columnsToggle',
            'colvis',
            'copy',
            'print',
            'excel'
        ])
        .withOption('fnRowCallback',myCallback)
        .withOption('order', [[ 3, "desc" ]])
        .withOption('stateSave',true);

    vm.dtColumns = [
        DTColumnBuilder.newColumn('File_Num').withTitle('File'),
        DTColumnBuilder.newColumn('Description').withTitle('Description'),
        DTColumnBuilder.newColumn('street').withTitle('Street'),
        DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
        DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
        DTColumnBuilder.newColumn('garages').withTitle('Garages'),
        DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
        DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
            return $filter('currency')(data, 'R ', 2);    //could use currency/date or any angular filter
        })

    ];
})
.controller('PagesListCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
    $scope.page = {
        title: 'Dashboard',
        subtitle: 'Place subtitle here...'
    };


});
function myCallback(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
    $('td', nRow).bind('click', function() {
    //$scope.$apply(function() {
           showTabDialog(aData);
    //});

   });
    return nRow;
};
function showTabDialog(ev) {
    console.log(ev.file_id);
    var data = "?db="+     $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
    var url = apiserv+"api.properties.view.php"+data;
    console.log(url);
    $http({url:url}).then(function(rs){
        console.log(rs.data[0]);
        $scope.propdata=rs.data[0];
        $mdDialog.show({
            controller: DialogController,
            templateUrl: 'pages/properties/tabDialog.tmpl.html',
            //parent: angular.element(document.body),
            targetEvent: ev,
            //onComplete: afterShowAnimation,
            //scope:$scope,
            //preserveScope: true
            locals: { propdata: $scope.propdata }
        })
        .then(function(propdata) {
            console.log(propdata);
            //$scope.$parent.propdata = propdata; // Still old data
            //vm.sname = propdata.street;
        });
    }, function(rs){
        console.log("error : "+rs.data+" status : "+rs.status);
    });
};

function DialogController($scope, $mdDialog, propdata) {
    $scope.propdata = propdata;
    $scope.form_size = "form-group-sm";
    $scope.font_size = "font-size-sm";
    $scope.hide = function(ret) {
    //$scope.$apply();  Throws an error
    $mdDialog.hide(ret);
}

$scope.changesize = function() {
    var fsize = $scope.form_size.split("-").pop();  // "form-group-xs";
    switch(fsize) {
        case "sm" : fsize = "md";
            break;
        case "md" : fsize = "lg";
            break;
        case "lg" : fsize = "sm";
            break;
    }
    $scope.form_size = "form-group-" + fsize;
    $scope.font_size = "font-size-" + fsize;
}
}

这就是我得到它的方式并且它起作用了,但是正如您所看到的,该对话框嵌套在控制器内部并且仅对该控制器有用:

app

.controller('PropertiesCtrl', function($scope,$rootScope,$http, DTOptionsBuilder, DTColumnBuilder, apiserv, $filter, $mdDialog, $mdMedia){
    $scope.page = {
        title: 'Dashboard',
        subtitle: 'Place subtitle here...'
    };

    $scope.getProperties = function(){
        $scope.data=[];
        //var url = 'http://www.filltext.com/?rows=10&fname={firstName}&lname={lastName}&delay=3&callback=JSON_CALLBACK';
        var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
        var url = apiserv+"api.properties.test.php"+data;
        $http.jsonp(url).success(function(data){
            $scope.data=data;
        });
    };


    var vm = this;

    function stateChange(iColumn, bVisible) {
        console.log('The column', iColumn, ' has changed its status to', bVisible);
    }

    // TO-DO: Rather load from a Factory promise, like here: https://github.com/l-lin/angular-datatables/issues/14
    // Example here: http://embed.plnkr.co/B9ltNzIRCwswgHqKD5Pp/preview
    var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name;
    var url = apiserv+"api.properties.test.php"+data;
    vm.dtOptions = DTOptionsBuilder.fromSource(url)

        .withBootstrap()
        // Active Buttons extension
        .withButtons([
            //'columnsToggle',
            'colvis',
            'copy',
            'print',
            'excel'
        ])

        .withOption('fnRowCallback',$scope.myCallback)
        .withOption('order', [[ 3, "desc" ]])
        .withOption('stateSave',true);


    vm.dtColumns = [
        DTColumnBuilder.newColumn('File_Num').withTitle('File'),
        DTColumnBuilder.newColumn('Description').withTitle('Description'),
        DTColumnBuilder.newColumn('street').withTitle('Street'),
        DTColumnBuilder.newColumn('bedrooms').withTitle('Bed'),
        DTColumnBuilder.newColumn('bathrooms').withTitle('Bath'),
        DTColumnBuilder.newColumn('garages').withTitle('Garages'),
        DTColumnBuilder.newColumn('car_port').withTitle('Car Ports').notVisible(),
        DTColumnBuilder.newColumn('Current_Monthly_Rental').withTitle('Rental').renderWith(function(data, type, full) {
            return $filter('currency')(data, 'R ', 2);    //could use currency/date or any angular filter
        })
        /*DTColumnBuilder.newColumn('file_id').withTitle('').withClass('dt-right').renderWith(function(data, type, full) {
           //return "<a  href='#/app/statement/"+full.id+"' class='btn btn-default'>View</a>";
            return "<a class=\"btn btn-default\" onclick='$(\"#myview\").click()'>View</a>";
        }).notSortable()*/
    ];




    $scope.showTabDialog = function(ev) {
        console.log(ev.file_id);
        var data = "?db="+ $rootScope.globals.currentUser.agents[$rootScope.globals.currentDB].db_name+"&file="+ev.file_id;
        var url = apiserv+"api.properties.view.php"+data;
        console.log(url);
        $http({url:url}).then(function(rs){
            console.log(rs.data[0]);
            $scope.propdata=rs.data[0];
            $mdDialog.show({
                    controller: DialogController,
                    templateUrl: 'pages/properties/tabDialog.tmpl.html',
                    //parent: angular.element(document.body),
                    targetEvent: ev,
                    //onComplete: afterShowAnimation,
                    //scope:$scope,
                    //preserveScope: true
                    locals: { propdata: $scope.propdata }
                })
                .then(function(propdata) {
                    console.log(propdata);
                    //$scope.$parent.propdata = propdata; // Still old data
                    //vm.sname = propdata.street;
                });
        }, function(rs){
            console.log("error : "+rs.data+" status : "+rs.status);
        });
    };

    function DialogController($scope, $mdDialog, propdata) {
        $scope.propdata = propdata;
        $scope.form_size = "form-group-sm";
        $scope.font_size = "font-size-sm";
        $scope.hide = function(ret) {
                //$scope.$apply();  Throws an error
                $mdDialog.hide(ret);
        }

        $scope.changesize = function() {
            var fsize = $scope.form_size.split("-").pop();  // "form-group-xs";
            switch(fsize) {
                case "sm" : fsize = "md";
                    break;
                case "md" : fsize = "lg";
                    break;
                case "lg" : fsize = "sm";
                    break;
            }
            $scope.form_size = "form-group-" + fsize;
            $scope.font_size = "font-size-" + fsize;
        }
    }

    $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        $('td', nRow).bind('click', function() {
            $scope.$apply(function() {
                $scope.showTabDialog(aData);
            });

        });
        return nRow;
    };

});

这是从任何控制器存储和检索用户的工厂:

app.factory('Auth', [, function () {
    function getUser() {
        return user;
     }
     var currentUser = getUser();
     return {
         currentUser: currentUser
     }]);

并使用它:

app.controller('controller', ['Auth', function(Auth) {
    var currentUser = Auth.currentUser;
}]);

并且不要忘记在页面上控制器之前包含新工厂。