trubliphone
trubliphone

Reputation: 4514

How to pass ng-model to controller

I have a very hierarchical data structure in JSON. I also have a re-usable (Django) template that gets bound to part of that structure. So, I need to know where in that structure I am for any given template. I am almost there:

http://jsfiddle.net/trubliphone/fd64rn3y/

The missing bit is being able to pass the current ng-model to a controller.

Here is some code (but the jsfiddle above shows more detail):

my_app.js:

var myApp = angular.module('myApp', []);

myApp.factory('$global_services', ['$http', function($http) {
  var data = {};
  $http.get("some_url", {format: "json"}) {
    /* THIS REQUEST RETURNS A BIG CHUNK OF HIERARCHICAL JSON */
    .success(function (data) {          
      data = data; 
    })
  });

  return {
    getPathFromModel: a_clever_fn_i_wrote_that_returns_a_string(),
    getModelFromPath: a_clever_fn_i_wrote_that_returns_a_model()
  }

}]);

myApp.controller('MyController', ['$scope', '$attrs', '$global_services', function( $scope, $attrs, $global_services ) {

  if ($attrs.currentModelPath) {
    /* if you passed current_model_path, get the current_model too */
    $scope.current_model_path = $attrs.currentModelPath;
    $scope.current_model = $global_services.getModelFromPath($scope.current_model_path);
  }
  else if ($attrs.currentModel) {
    /* if you passed current_model, get the current_model_path too */
    $scope.current_model = $attrs.currentModel;
    $scope.current_model_path = $global_services.getPathFromModel($scope.current_model);
  }
}]);

my_template.html:

<div ng-app="myApp">  
  <div ng-controller="MyController" current_model_path="data">
    {{current_model.name}}:
    <ul ng-repeat="child in current_model.children">
        <input type="text" ng-model="child.name"/>  {{ child.name }}        
        <!-- LOOK: HERE IS A NESTED CONTROLLER -->
        <div ng-controller="MyController" current_model="child">      
          {{current_model.name}}:
          <ul ng-repeat="child in current_model.children">
            <input type="text" ng-model="child.name"/> {{ child.name }}
          </ul>
      </div>
    </ul>
  </div>    
</div>

The problem is in the "div" element for the nested controller; I pass the {{child}} ng variable as an attribute, but when the controller recieves it, it just interprets it as the JavaScript string "child". How can I pass the actual model object?

Thanks.

Upvotes: 0

Views: 878

Answers (1)

racamp101
racamp101

Reputation: 516

  <div ng-controller="MyController" ng-init="data = child">

this will add an object to the inner scope named data.

Upvotes: 2

Related Questions