javascript - Angular JS, is it possible to set ng-include or ng-controller dynamically? -
i new angular js , through research looks not possible wanted double-check/see if there alternative solution have similar result.
what want populate page json file, , load customized li using url on json file. this:
json/inside controller:
function exctrl($scope) { $scope.examples = [ {name:"example", num: 1, url:"website.html"} ]; }
js (inside js)
<ul ng-controller="exctrl"> <li ng-repeat="example in examples"> <div ng-include src="folder/{{example.url}}> </div> </li> </ul>
solution :
<ul ng-controller="exctrl"> <li ng-repeat="example in examples"> <div ng-include src="example.url"> </div> </li> </ul>
where now:
function exctrl($scope) { $scope.examples = [ {name:"example", num: 1, url:"folder/website.html"} ]; }
from documentation:
nginclude|src
–{string}
– angular expression evaluating url. if source string constant, make sure wrap in quotes, e.g.src="'mypartialtemplate.html'"
.
in case makes sense set custom ngresource. in controller, inject resource , query json, assign json scope variable.
angular.module("foo", "ngresource") .factory("resourcetype", function($resource){ return $resource("/resourcetype/:id", {id: "@id"}, { "update": {method:"put"}}); }) .controller("exctrl" function($scope, resourcetype){ $scope.examples = resourcetype.query(); });
you set ng-include url loop on resource.
also, don't {{}} variable name.
edit:
i going give plunker, seems acting up. here inline source like. sake of clarity, removed resource piece. imagine want put when decide retrieve json remotely.
<!doctype html> <html ng-app="angularjs-starter"> <head lang="en"> <meta charset="utf-8"> <title>custom plunker</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script> <script src="app.js"></script> </head> <body ng-controller="mainctrl"> <ul ng-controller="mainctrl"> <li ng-repeat="example in examples"> if {{example.url}} valid, load in div. <div ng-include="example.url"> </div> </li> </ul> </body> </html> var app = angular.module('angularjs-starter', []); app.controller('mainctrl', function($scope) { $scope.examples = [ {name:"example", num: 1, url:"example.html"} ]; });
edit: plunk
Comments
Post a Comment