AngularJS Restful Routing

后端 未结 4 1389
滥情空心
滥情空心 2021-01-05 02:44

I\'m trying to structure my app using the Restful/Ruby convension //[method]/[id]. How I\'ve done it previously when using a server-side MVC fra

4条回答
  •  不知归路
    2021-01-05 02:58

    To conform to existing routing systems like Rails, the ability to define the method in the route is now available. I created a super simple solution that allows routes to call a method based on the route definition and a directive in the view. I think ui-router is not conventional and is too complicated for a such a "should be" core feature.

    The project is called ngMethod and is located at: https://github.com/jzumbrun/ng-method.

    An example of its use is: https://github.com/jzumbrun/chrome-apps-angularjs-bootstrap

    So if I have a route like so:

    $routeProvider.
            when('/contacts/new', {
                controller: 'ContactsController',
                method: 'new',
                templateUrl: $configProvider.template('contacts/form.html'),
            });
    
        $routeProvider.
            when('/contacts/:id/edit', {
                controller: 'ContactsController',
                method: 'edit',
                templateUrl: $configProvider.template('contacts/form.html'),
            });
    

    and I have ng-method in the contacts/form template:

    ...

    Then the ng-method will call either $scope.edit() or $scope.new() in the ContactsController. Than the contacts/form template can be shared, and depending on the route call the correct method to load the data. This style is now more "Angularjs" and the loading the code is much like angular calling to modules and controllers.

    The full directive that makes this happen is less than 20 lines of code:

    app.directive('ngMethod', ['$route', function($route) {
        return {
            // Restrict it to be an attribute in this case
            restrict: 'A',
            // responsible for registering DOM listeners as well as updating the DOM
            link: function(scope, element, attrs) {
    
                // Call method without params. Use $routeParams
                if(angular.isFunction(scope[attrs.ngMethod])){
                    scope[attrs.ngMethod]();
                // default to the route method if attrs.ngMethod is empty
                } else if(angular.isObject($route.current) 
                    && angular.isString($route.current['method']) 
                    && angular.isFunction(scope[$route.current['method']])){
                    scope[$route.current['method']]();
                }
            }
        };
    }]);
    

提交回复
热议问题