AngularJS - 指令范围模型在没有调试器的情况下不会更新

时间:2017-01-03 18:18:15

标签: angularjs angularjs-directive angularjs-scope

对于创建/编辑网站内容,我有一个带有一些标签的表单(用于创建标签系统的按钮,因为用户可能想要添加另一个"标签"等等)并且我使用了指示显示所选选项卡:

<form name="form" novalidate>
    <div class="tabsContainer">
        <!--some button making the idea of tabs system-->
    </div>

    <div class="contentDataContainer">
        <content-form ng-model="VM.CurrentContent" page-features="VM.PageFeatures"></content-form>
    </div>
</form>

当用户想要编辑内容时,我向Web服务请求内容数据:

loadData = function () {
    var deferred = $q.defer();

    ContentsService.GetContentToCreateEdit({ id: vm.IdContent })
        .then(function(response)
        {
            try {
                if (vm.IdContent <= 0 || (response.ResultOperation === ResultEnum.Success && exists(response.ResultObject.Contents)))
                {
                    vm.Model = ContentVM.GetModelToShow(response.ResultObject.Contents);
                    vm.CurrentContent = vm.Model[0];
                }
                else 
                {
                    //some like with error messages
                }
            }
            catch (err) { }

        deferred.resolve();              
    }, function () {
        deferred.resolve();
    });

    LoadingService.Load(deferred.promise, 'first');
};

指令的模型必须更新。

指令控制器:

vm.Model = { Id: 0 };

function init()
{            
    vm.Model = exists($scope.model) ? $scope.model : getDefaultContentInfo(); 

    if(isStringEmpty(vm.Model.Price)) vm.Model.Price = "";
    vm.Model.PriceText = vm.Model.Price;
    vm.Model.IsIntervalDate = !isStringEmpty(vm.Model.EndDate) && vm.Model.EndDate != vm.Model.StartDate;
};

init();

$scope.$watch($scope.model, function () {
    init();
}, true);

如果我在debugger函数中添加了init(),那么该指令会与$scope.model完美匹配,但如果我还没有... {/} p>

有人可以解释这里发生了什么,我该如何解决?

我已尝试使用$scope.$apply(),但我收到了摘要错误,并且我已尝试使用$timeout(),但指令的模型并未更新。

$timeout(function () {
    init();

    $scope.$watch($scope.model, function () {
        init();
    }, true);
},500);

2 个答案:

答案 0 :(得分:0)

进入初始化时,可能未设置vm.Model。使用调试器,您需要等待足够的时间来设置变量 如果getDefaultContentInfo()返回一个promise,那么你需要做的是将变量设置为promise中返回的then函数中的数据。

答案 1 :(得分:0)

在实施表单验证后,我需要显示模型错误,然后再次出现问题。经过许多头痛并找到了问题后,最终结束了。

在我的$scope.$watch

$scope.$watch($scope.model, function () {
    init();
}, true);

watchExpression 必须是幂等性的,所以我将代码更改为

$scope.$watch('model', function () {
    init();
}, true);

现在有效!!!

有关更多文档click here

相关问题