Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have some json attached to a data attribute on a page. The json data is used to build a table in angularjs. I'm using coffeescript and haml.

    app = angular.module("myApp", [])

    app.controller "TableCtrl", ($scope) ->
      $scope.table =  $("#mydata").data("myjson")


    #table{"ng-app"=>"myApp","ng-controller" =>"TableCtrl"}
      %table
        %tbody
          %tr{"ng-repeat"=>"(i,item) in table" }}"}
            %td {{item.name}}

The page loads the data into a table. Elsewhere on the page the json on the data attribute can be changed by a user with jquery. How can I have 2-way binding between the json data and the table? i.e I want the table to change as the json on the data attribute is changed locally.

share|improve this question
    
This is a very strange use case. Why is the data coming from jQuery instead of AngularJS? If at all possible, you should get the data into a model/service. –  Josh David Miller Apr 17 '13 at 23:46
    
I'm updating an old app that was full of jquery, just trying to understand different parts as I work through it –  raphael_turtle Apr 17 '13 at 23:49
    
I would try to pull the data out as the very first priority; otherwise there is going to be a lot more headaches down the line. AngularJS is very different than jQuery. –  Josh David Miller Apr 18 '13 at 0:22

1 Answer 1

What you need is to tell AngularJS to observe $("#mydata").data("myjson") for any changes and then update $scope.table when a change occurs. Try adding the following code to your controller (sorry I don't know coffeescript).

$scope.$watch(
    function () { return $("#mydata").data("myjson");}, 
    function(newJson) {
        $scope.table = newJson;
    },
    true
);
share|improve this answer
1  
Passing strings to $watch only works for scope properties. You need to use a function instead. –  Josh David Miller Apr 17 '13 at 23:46
    
@JoshDavidMiller - Right, my careless! Thanks for pointing it out. –  tamakisquare Apr 17 '13 at 23:53
    
that still doesn't update the data displayed in the table –  raphael_turtle Apr 17 '13 at 23:56
1  
No, it should say $scope.$watch( function() { return $("#mydata").data("myjson"); }, ...). –  Josh David Miller Apr 18 '13 at 0:20
    
Thanks @JoshDavidMiller once again. My brain is surely not working today. –  tamakisquare Apr 18 '13 at 0:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.