【问题标题】:AngularJS : changing the object not triggered in `$watch` methodAngularJS:更改未在`$watch`方法中触发的对象
【发布时间】:2015-10-16 00:34:06
【问题描述】:

作为一个基本的,我保留一个带有一些默认值的对象。一旦我从服务器获取值,我就会更新对象。当我更新时不会触发$watch 方法。有人帮我知道这里的原因吗?

我的控制器.js:

$scope.graphInfo = {"ActualPercentage" : 30, "Type" : "Mechanical" };
        // default sets

        $scope.conractorInfo = function ( contractor ) {

            $location.search('id', contractor.Id);

            server.contractor.get({id:$routeParams.id, contid:contractor.Id}).$promise.then(function (data) {

                $scope.contractor = data;
                $scope.graphInfo.ActualPercentage = Number($scope.contractor.ActualPercentage);
                $scope.graphInfo.Type = $scope.contractor.Type;
                //updating object
            });

        }

我的带有指令的模板:

    <plan-vs-actual data="graphInfo"></plan-vs-actual>

//getting graph info.

我的指令:

    var planVsActual = function ($timeout) {

        return {

            replace : true,

            scope : {

                data : '='
            },

            template : "<div id='pieGraph'></div>",

            link : function ( scope, element, attr ) {


                var width = element.width(), 
                height = element.height(),
                radius = Math.min(width, height) / 1.2;

                var color = d3.scale.ordinal().range(["#ffff00", "#1ebfc5"]);

                var pie = d3.layout.pie().sort(null).value(function(d) { return d });

                var arc = d3.svg.arc().outerRadius(radius - 90).innerRadius(radius - 85);

                var svg = d3.select("#pieGraph").append("svg").attr("width", width).attr("height", height)
                         .append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

                scope.$watch ('data', function ( newValue, oldvalue ) {

                    console.log( newValue );
//after i am updating using server values, not updating here.

                });
    }
    }
    }

【问题讨论】:

标签: angularjs angular-directive


【解决方案1】:

$watch的第三个参数设置为true

修改喜欢,

scope.$watch ('data', function ( newValue, oldvalue ) {

    console.log( newValue );

 }, true);

// put true to watching properties

第三个参数是 objectEquality,它将使用 angular.equals 比较对象相等性,而不是比较引用相等性。

这里是DOC

不确定试试看。

【讨论】:

    猜你喜欢
    • 2013-03-21
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 2013-03-29
    • 2021-01-23
    相关资源
    最近更新 更多