我在JSON中有一个非常分层的数据结构。我还有一个可重用的(Django)模板,它被绑定到该结构的一部分。所以,我需要知道我在任何给定模板的结构中的位置。我几乎那里:
http://jsfiddle.net/trubliphone/fd64rn3y/
缺失的位能够将当前的ng模型传递给控制器。
这是一些代码(但上面的jsfiddle显示了更多细节):
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>
问题在于嵌套控制器的“div”元素;我将{{child}}
ng变量作为属性传递,但是当控制器收到它时,它只是将其解释为JavaScript字符串“child”。如何传递实际模型对象?
感谢。
答案 0 :(得分:2)
<div ng-controller="MyController" ng-init="data = child">
这会将一个对象添加到名为data的内部作用域。