AngularJS:$ $范围的手表是不是在自定义指令更新值从$获取资源 [英] AngularJS : $scope.$watch is not updating value fetched from $resource on custom directive

查看:191
本文介绍了AngularJS:$ $范围的手表是不是在自定义指令更新值从$获取资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有与驾驶我疯了自定义指令的问题。
我试图创建以下自定义(属性)指令:

I'm having an issue with custom directives that's driving me crazy. I'm trying to create the following custom (attribute) directive:

angular.module('componentes', [])
    .directive("seatMap", function (){
        return {
            restrict: 'A',
            link: function(scope, element, attrs, controller){

                function updateSeatInfo(scope, element){
                    var txt = "";
                    for (var i in scope.seats)
                        txt = txt + scope.seats[i].id + " ";
                    $(element).text("seat ids: "+txt);
                }

                /* 
                    // This is working, but it's kind of dirty...
                    $timeout(function(){updateSeatInfo(scope,element);}, 1000);
                */

                scope.$watch('seats', function(newval, oldval){
                    console.log(newval, oldval);
                    updateSeatInfo(scope,element);
                });
            }
        }
    });

这属性类型指令(称为seatMap)正在试图展示座ID列表(例如,一个剧院),我会从服务器通过$资源服务获取(见code以下)成格(元素)。

This "attribute-type" directive (called seatMap) is trying to show a list of seat ids (e.g, for a theatre) which I'll fetch from the server via $resource service (see code below) into a div (element).

我使用它与这个简单的HTML部分:

I'm using it with this simple partial html:

<div>
    <!-- This is actually working -->
    <ul>
        <li ng-repeat="seat in seats">{{seat.id}}</li>
    </ul>

    <!-- This is not... -->
    <div style="border: 1px dotted black" seat-map></div>
</div>

这是加载范围控制器:

And this is the controller which is loading the scope:

function SeatsCtrl($scope, Seats) {
    $scope.sessionId = "12345";
    $scope.zoneId = "A";
    $scope.seats = Seats.query({sessionId: $scope.sessionId, zoneId: $scope.zoneId});
    $scope.max_seats = 4;
}

在哪里座位是使用$资源从服务器获取一个JSON一个简单的服务

Where "Seats" is a simple service using $resources to fetch a JSON from the server

angular.module('myApp.services', ['ngResource'])
    .factory('Seats', function($resource){
        return $resource('json/seats-:sessionId-:zoneId.json', {}, {});
    })
;

app.js(asientos_libres.html是我一直在使用部分):

app.js (asientos_libres.html is the partial I've been using):

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'componentes']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/view1', {templateUrl: 'partials/asientos_libres.html', controller: SeatsCtrl});
    $routeProvider.otherwise({redirectTo: '/view1'});
  }]);

问题是,即使我成立了一个范围。$表的指令的链接功能,这样的范围可以检查是否席位的属性已经改变,更新ID列表,它不是此刻$ scope.seats工作是在控制器改变(我们称之为查询)。

The problem is, even though I set up a "scope.$watch" in the link function of the directive so that the scope can check whether "seats" attribute has changed to update the list of ids, it isn't working at the moment $scope.seats is changing in the controller (when we call "query").

正如你可能会在code看到的,我做了使用$超时延迟推出updateSeatInfo的一个尝试,但恐怕这不是迄今为止最聪明的解决方案......

As you might see in the code, I made a try using $timeout to delay the launch of "updateSeatInfo", but I'm afraid it's not the smartest solution by far...

我也试图不使一个JSON请求,但使用$ scope.seats一个硬codeD字典和它的作品,如此看来它是同步的问题。

I also tried to not to make a JSON request, but use a hard-coded dictionary in $scope.seats and it works, so it seems it's a matter of synchrony.

注:updateSeatInfo只是一个测试功能,实际的功能,我会用更复杂一点

如何应付它的任何想法?

Any idea about how to cope with it?

感谢您了很多事先!

编辑1:补充app.js,在这里我使用路由器来调用SeatsCtrl,感谢SUPR的意见。不过,我仍然有同样的问题。

Edit 1: Added app.js, where I'm using router to call SeatsCtrl, thanks to Supr for the advice. However, I'm still having the same issue.

编辑2:!(?)解决
好!我似乎找到了解决办法,这可能不是最好的,但它的正常工作! :)
至于我能在这里看到 http://docs.angularjs.org/api/ng.$timeout 我们可以用$超时(超过setTimeout的包装)的无延迟!这是伟大的,因为我们没有人为地拖延$超时里面我们code的执行,但是我们正在做的指令,不运行它,直到异步请求已经完成。

Edit 2: Solved!(?) Ok! It seems I found a solution, which may not be the best, but it's working properly! :) As far as I could see here http://docs.angularjs.org/api/ng.$timeout, we can use $timeout (a wrapper over setTimeout) with no delay! This is great because we aren't artificially delaying the execution of our code inside $timeout, but we're making the directive not to run it until the asynchronous request has finished.

希望它会为长期等待的要求工作,太...

Hope it will work for long-wait requests, too...

如果有人知道一个更好的办法来解决它,请告知!

If someone knows a better way to fix it, please tell!

推荐答案

的问题是,手表比较基准,而不是默认的对象。添加,真正到了年底有它的比较值,而不是。

The issue is that watch compares the reference instead of the object by default. Add ,true to the end to have it compare the value instead.

scope.$watch('seats', function(newval, oldval){
                console.log(newval, oldval);
                updateSeatInfo(scope,element);
            }, true);

这篇关于AngularJS:$ $范围的手表是不是在自定义指令更新值从$获取资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆