角度视图不更新新数据 [英] Angular View Not Updating with New Data

查看:26
本文介绍了角度视图不更新新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个 Angular 新手,如果这很明显,我很抱歉.

我有一个返回对象数组的后端.检索它们后,我移至下一页,我需要为每个对象显示一个复选框.我可以成功检索它们,因此我将浏览器的位置更改为应显示复选框但未显示任何内容的下一页.我尝试使用 $scope.$apply() 但是它抛出一个错误,指出摘要已经在发生,但我认为这是正确的,因为我使用了包裹在 $scope.$apply() 中的 ng-click 我认为?

我可以在控制台中看到成功打印出的服务,但是它们没有出现在页面中.不确定我在这里做错了什么?

在我的初始视图中:

<div class="form-group"><select id="main_service" name="main_service" class="form-control" ng-model="mainService"><option>请选择...</option><option ng-repeat="service in mainServices" value="{[{service}]}">{[{service}]}</option></选择>

<div class="form-group"><button class="btn btn-primary" type="submit" ng-click="updateServices()">继续</button>

</表单>

在我的控制器中:var ProfessionalSignupControllers = angular.module('professionalSignupCtrls', [])

professionalSignupControllers.controller('professionalQuestions', function($scope, $http, Service, $sce, $routeParams,$location){$scope.mainService = "";$scope.services = [];$scope.updateServices = function(){Service.getServices($scope.mainService).成功(功能(数据){$scope.services = 数据控制台日志($scope.services)//$scope.$apply();抛出摘要错误!$location.path('/services');}).错误(功能(数据,错误){event.preventDefault();警报(哦亲爱的")});};

})

在我的服务部分:

<div ng-repeat="service in services" class="checkbox"><label><input type="checkbox" name="service[]" value="{[{service.id}]}" ng-model="user.services">{[{service.label}]}

我的服务服务(坏名):

angular.module('servicesService', []).factory('服务', 函数($http) {返回 {获取服务:功能(标签){return $http.get('/api/service?searchTerm='+tag)}}});

我的应用配置:

app.config(['$routeProvider', '$locationProvider','$interpolateProvider',功能($routeProvider,$locationProvider,$interpolateProvider){$routeProvider.当('/开始',{templateUrl: '/js/partials/start-professional-questions.html',控制器:'专业问题'}).当('/服务',{templateUrl: '/js/partials/services-professional-questions.html',控制器:'专业问题'}).除此以外({重定向到:'/开始'});$interpolateProvider.startSymbol('{[{').endSymbol('}]}');}]);

我使用 {[{ }]} 进行插值,否则它将使用 Blade 语法进行分类

解决方案

你在 angular 范围内,所以你不需要触发 $scope.$apply().仅当您超出角度范围时才需要.

<块引用>

关于您的问题:

您正在服务中返回承诺对象.因此返回的数据仅在该控制器中可用.如果您要移至下一页,则该数据将不可用.

如果要共享数据,则必须将其存储在服务中.

为您服务:

 angular.module('servicesService', []).factory('Service', function($http, $q) {无功数据;返回 {获取数据:函数(){返回数据;},获取服务:功能(标签){var defer = $q.defer();$http.get('/api/service?searchTerm='+tag).then(function(response) {数据 = 响应;defer.resolve(响应);});返回 defer.promise;}}});

现在在另一个控制器中,您可以使用 getData()

访问数据

在您的控制器中,您可能需要稍微修改一下:

$scope.updateServices = function(){Service.getServices($scope.mainService).then(function(data){$scope.services = 数据控制台日志($scope.services)$location.path('/services');},函数(数据,错误){event.preventDefault();});};

在您的第二个控制器中,您可以通过 Service.getData()

访问它

由于您对两个视图使用相同的控制器,您需要使用 if 条件来检查 route 并单独获取数据.否则,您最终可能会再次触发服务呼叫.

I'm a bit of an Angular newbie so sorry if this is obvious.

I have a backend which returns an array of objects. After I retrieve them, I move to the next page and i need to display a checkbox for each of the objects. I can successfully retrieve them, so I change the location of browser to the next page where the checkboxes should be displayed but nothing is being displayed. I tried using $scope.$apply() however it throws an error stating that a digest is already taking place but I think that's correct because I've used ng-click which is wrapped in a $scope.$apply() I think?

I can see the services being printed out in the console successfully, however they don't appear in the page. Not sure what I'm doing wrong here?

In my starting view:

<form>
    <div class="form-group">
        <select id="main_service" name="main_service" class="form-control" ng-model="mainService">
             <option>Please Select...</option>
             <option ng-repeat="service in mainServices" value="{[{service}]}">{[{service}]}</option>  
        </select>
    </div>
    <div class="form-group">
        <button class="btn btn-primary" type="submit" ng-click="updateServices()">Continue</button>
    </div>
</form>

in my controller: var professionalSignupControllers = angular.module('professionalSignupCtrls', [])

professionalSignupControllers.controller('professionalQuestions', function($scope, $http, Service, $sce, $routeParams,$location){
$scope.mainService = "";
$scope.services = [];

$scope.updateServices = function(){
    Service.getServices($scope.mainService)
        .success(function(data) {
            $scope.services = data
            console.log($scope.services)
            //$scope.$apply(); throws digest error!
            $location.path( '/services' );
        })
        .error(function(data, error) {
            event.preventDefault();
            alert("Oh Dear")
        });
};

})

In my services partial:

<div>
    <div ng-repeat="service in services" class="checkbox">
        <label><input type="checkbox" name="service[]" value="{[{service.id}]}" ng-model="user.services">{[{service.label}]}</label>
    </div>
</div>

My servicesService (bad name):

angular.module('servicesService', [])

.factory('Service', function($http) {

    return {
        getServices : function(tag) {
            return $http.get('/api/service?searchTerm='+tag)
        }
    }
});

My app config:

app.config(['$routeProvider', '$locationProvider','$interpolateProvider',
function($routeProvider,$locationProvider,$interpolateProvider) {

    $routeProvider.
        when('/start', {
            templateUrl: '/js/partials/start-professional-questions.html',
            controller: 'professionalQuestions'
        }).
        when('/services', {
            templateUrl: '/js/partials/services-professional-questions.html',
            controller: 'professionalQuestions'
        }).
        otherwise({
            redirectTo: '/start'
        });

    $interpolateProvider.startSymbol('{[{').endSymbol('}]}');

    }
]);

I'm using {[{ }]} for interpolation as otherwise it would class with the Blade syntax

解决方案

You're in angular scope and so you need not trigger $scope.$apply(). it's required only when you're out of angular scope.

Regarding your issue:

You're returning the promise object in the service. So the data returned is only available in that controller alone. If you're moving to next page then that dat won't be available.

If you want to share the data, then you must store that inside the service.

In your service:

 angular.module('servicesService', [])

.factory('Service', function($http, $q) {
    var data;
    return {
        getData: function() {
           return data;
        },
        getServices : function(tag) {
            var defer = $q.defer();
            $http.get('/api/service?searchTerm='+tag).then(function(response) {
                data = response;
                defer.resolve(response);
            });
            return defer.promise;
        }
    }
});

Now in your another controller, you can access the data using getData()

In your controller, you may need to modify it a bit:

$scope.updateServices = function(){
    Service.getServices($scope.mainService).then(function(data){
            $scope.services = data
            console.log($scope.services)
            $location.path( '/services' );
        }, function(data, error) {
            event.preventDefault();
        });
};

In your second controller, you can access it via Service.getData()

Since you're using same controller for both views, you need to use an if condition to check the route and get the data alone. Else you may end up firing the service call again.

这篇关于角度视图不更新新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆