Now that Angular says using ng-init
is not appropriate in most cases (source), what's the right way of passing data in, when I don't have the data I need in $scope
?
I'm trying to do let future developers use a simple controller to template data sourced from a service and applied via $scope
to a partial, but I need a way for them to pass an id from the template to the controller to get the correct data from the service.
Imagine Widget1 has partial widget1.html
and gets its data from http://localhost/widget1.json
.
Previously, I would have added Widget1 to my app by inserting the following into the correct place, and passing the widgetID
using ng-init
.
<div class='simple-widget' ng-include src="'widgets/widget1.html'" ng-init=" widgetID = 'widget1'"></div>
widget1.html:
<div class='simple-widget' ng-controller="SimpleWidget">
<p>Hello {{ data.user.name }},
<p>{{ data.message }}</p>
</div>
All of the data object will come from the DataService, as seen below.
Controller:
angular.module('myApp.controllers', [])
.controller('SimpleWidget', ['$scope','StatService',function($scope,DataService) {
$scope.data = DataService.get({id:$scope.widgetID});
}])
Now that ng-init is discouraged, where can I put the id so that it arrives in the controller for using in my service?
Copyright Notice:Content Author:「John」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/23484054/whats-the-angular-way-to-get-data-from-the-partial-into-the-controller