У меня очень иерархическая структура данных в JSON. У меня также есть повторно используемый (Django) шаблон, который привязан к части этой структуры. Итак, мне нужно знать, где в этой структуре я для любого заданного шаблона. Я почти есть:Как передать ng-модель контроллеру
http://jsfiddle.net/trubliphone/fd64rn3y/
недостающее бит в состоянии передать текущий нг-модели к контроллеру.
Вот код (но 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». Как передать реальный объект модели?
Спасибо.
Спасибо. Кажется, это работает. Тем не менее, я думал, что использование ng-init было недооценено вне ng-repeat? – trubliphone
Все нахмурено в эти дни просто разумно используйте – racamp101
Хотите отметить этот ответ? – racamp101