简体   繁体   中英

How do I reload my navbar upon a successful form submission?

I am using angular.js. I have a controller for my navbar which looks as follows.

var controllers = angular.module('controllers', []);

controllers.controller('NavbarController', ['$scope', '$http',
    function ($scope, $http) {
        $http.get('/api/courses')
        .success(function(data) {
            $scope.courses = data.objects;
        });
    }
]);

This will give me all the courses which have been created. I put it on the navbar like so:

<ul class="dropdown-menu">
  <li  ng-repeat="course in courses">
    <a href="#/course/course_id/{{ course.id }}">{{ course.name }}</a>
  </li>
</ul>

This works when I load my page. However, I have a form to create a NEW course, which also works. However, after this has been successfully submitted, the navbar will not contain the class until I completely reload the page. This is my controller which creates a new course.

controllers.controller('CreateCourseController', ['$scope', '$http',
    function($scope, $http) {
        $scope.form_data = {};
        $scope.submitForm = function() {
            $http.post('/api/courses', $scope.form_data).
            success(function(data) {
              // here, I want to add this item into the navbar selection somehow
            });
        }
    }
]);

what would be the best way in angular to add this newly added class into the navbar, cleanly?

You could use $broadcast to send a message that the nav needs to be updated and use $on to listen for the event. See: https://docs.angularjs.org/api/ng/type/ $rootScope.Scope

Maybe something like this:

var controllers = angular.module('controllers', []);

controllers.controller('NavbarController', ['$scope', '$http',
function ($scope, $http) {
    var updateNav = function() {
        $http.get('/api/courses')
            .success(function(data) {
                $scope.courses = data.objects;
            });
    };

    // Init
    updateNav();

    // Subscribe
    $scope.$on('nav:updated', updateNav() );

}]);

controllers.controller('CreateCourseController', ['$scope', '$http',
function($scope, $http) {
    $scope.form_data = {};
    $scope.submitForm = function() {
        $http.post('/api/courses', $scope.form_data).
        success(function(data) {
            // here, I want to add this item into the navbar selection somehow
            $scope.$broadcast('nav:updated');
        });
    }
}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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