当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Cant get data binding between Factory, controller and directive to work

问题描述:

So think I am doing the right thing.

Basically, I have a factory that (among other things) gets some data form the API basically a large JSON type object with a ton of stuff using restangular.

This is then stored in $scope.cvSkills. $scope.cvSkills is initiated in the beginning of the controller.

knowledge.controller('cvedit', function ($scope, cvFactory){

$scope.iAm = "";

$scope.CV = "";

$scope.cvskills= "";

cvFactory.getSkills(function(cvSkills){

$scope.cvskills = cvSkills;

console.log("got " + $scope.cvskills.length);

})

})

My problem is now getting the updated data to the directive so we can get d3 to make a nice tree.

Tried:

knowledge.directive('skillTree', function(){

function link(scope,element, attr){

scope.$watch('attr.cvSkills', function() {

console.log("CVSkills updated " + attr.cvSkills.length);

});

var cvSkills = attr.cvSkills;

console.log("Got this back " + cvSkills.length);

for (var i in cvSkills) {

console.log("ID: " + i + " DATA: " + cvSkills[i])

}

}

return {

link: link,

//scope: { cvskills: '=' },

restrict: 'E'

}

Problem is that the scope watch and the data passed in is whatever cvskills was initiated as, so how do I get it to react to updates?

<skill-tree cv-skills="{{cvskills}}"></skill-tree>

This is how I call it, so SHOULD it react, or am I just doing it wrong?

网友答案:
<skill-tree cv-skills="cvskills"></skill-tree>

So for this to work we need to make a couple changes to your directive.

knowledge.directive('skillTree', function()
{
    function link(scope)
    {
        scope.$watch('cvSkills', function (cvSkills) // we're watching the scope's cvSkills not the attribute's
        {
            console.log("Got this back " + cvSkills.length);

            for (var i in cvSkills)
            {
                console.log("ID: " + i + " DATA: " + cvSkills[i])
            }
        }, true);
    }

    return {
        link: link,
        scope: {
            cvSkills: '=' // this was correct, almost
        },
        restrict: 'E'
    }
});

I notice you tried adding cvSkills to your scope which was certainly a good start as that's what we need to $watch rather than the element's attribute.

分享给朋友:
您可能感兴趣的文章:
随机阅读: