0

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.

3
  • 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. Commented Apr 17, 2013 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 Commented Apr 17, 2013 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. Commented Apr 18, 2013 at 0:22

1 Answer 1

0

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
);
7
  • 1
    Passing strings to $watch only works for scope properties. You need to use a function instead. Commented Apr 17, 2013 at 23:46
  • @JoshDavidMiller - Right, my careless! Thanks for pointing it out. Commented Apr 17, 2013 at 23:53
  • 1
    No, it should say $scope.$watch( function() { return $("#mydata").data("myjson"); }, ...). Commented Apr 18, 2013 at 0:20
  • Thanks @JoshDavidMiller once again. My brain is surely not working today. Commented Apr 18, 2013 at 0:25
  • @raphael_turtle - Your case needs to have the flag for comparing object for equality rather than for reference to true. Updated my answer. Try again. Commented Apr 18, 2013 at 1:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.