AngularJS传递数据以查看

时间:2017-09-20 13:02:18

标签: javascript angularjs

我有一个如下控制器:

 angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {

    $scope.selectedCourse = [];
    $scope.getCourse = function(id){
      Course.getCourse(id)
        .then(function(response) {
          $scope.selectedCourse = {
              course_name     : response.data.data['name'],
              course_code     : response.data.data['code']
          }
          $location.path('/course');
        })
        .catch(function(response) {
          toastr.error(response.data.message, response.status);
        });
    };
  });   

观点如下:

<div class="ten wide column" ng-controller="CoursesCtrl">
    <h2 class="ui header">
        {{selectedCourse.course_name}}
    </h2>
    <h4 class="ui header">
        Instructor: {{selectedCourse.course_code}}
    </h4>
</div>

我无法将数据传递到具有位置路径的视图中:course:

密切关注代码,是否存在遗漏或需要考虑的问题。

3 个答案:

答案 0 :(得分:0)

因为您已在selectedCourse函数中编写了getCourse的代码,因此您必须在selectedCourse函数之外编写getCourse

答案 1 :(得分:0)

angular.module('myApp').controller('CoursesCtrl', function($scope, $auth, $location, toastr, Course, $http) {


$scope.selectedCourse ={}; //here was the mistake

$scope.getCourse = function(id){
  Course.getCourse(id)
    .then(function(response) {

      $scope.selectedCourse = {
          course_name     : response.data.data['name'],
          course_code     : response.data.data['code']
      }

      $location.path('/course');

    })
    .catch(function(response) {
      toastr.error(response.data.message, response.status);
    });
};
});

答案 2 :(得分:0)

在您的代码$scope.selectedCourse中声明为数组。将其声明为$scope.selectedCourse = {};

的目的
angular.module('myApp').controller('CoursesCtrl', function ($scope, $auth, $location, toastr, Course, $http) {

//Loading the value based on the existance in parent controller.
$scope.selectedCourse = ($scope.$parent.selectedCourseData)? $scope.$parent.selectedCourseData: {};

        $scope.getCourse = function (id) {
            Course.getCourse(id)
                .then(function (response) {
                    $scope.selectedCourse = {
                        course_name: response.data.data['name'],
                        course_code: response.data.data['code']
                    }
                    //Keeping the value in a parent controller
                    $scope.$parent.selectedCourseData = $scope.selectedCourse;
                    $location.path('/course');

                })
                .catch(function (response) {
                    toastr.error(response.data.message, response.status);
                });
        };
    });