javascript - AngularJS Make a scope variable available before view is loaded -
i creating set of select boxes, bound list of values in view using directive select tag in it, on div. populated values, after rendered want set value depending on stored value in it.
i trying setting model value in ng-init
, using function call in controller initializes array stored values in it.
however, array undefined when select boxes rendered , ng-init
called.
how ensure variable set when ng-init
called on select boxes?
angular.module('myapp') .controller('aclctrl', function() { $scope.retrievesetvalues(id) { //.then promise stored values, defined in factory, sets variable accessed in initializeselects() } $scope.retrievesetvalues($scope.myid); }
view:
selector directive:
.directive("selector", [ function() { return { controller: function() { this.myvalues= ['a', 'b', 'c']; }, require: 'ngmodel', controlleras: 'ctrl', scope: { 'ngmodel': '=' }, template: '<select ng-model="innermodel" ng-change="updateinnermodel()" ng-options="v v in ctrl.myvalues"> </select>', link: function(scope, elem, attrs, ngmodelcontroller) { scope.innermodel = scope.ngmodel; scope.updateinnermodel = function() { ngmodelcontroller.$setviewvalue(scope.innermodel); }; } }; } ])
the problem don't see variable setting in scope call retrievesetvalues()
in access ng-init initializeselects()
call.
i have tried both, calling in controller , calling ng-init
before try access saved values in initializeselects()
.
i new angular, understanding of how whole digest cycle works newbie level. :(
any appreciated!!
you can try that:
function selector() { return { controller: function() { this.myvalues= ['a', 'b', 'c']; }, require: 'ngmodel', controlleras: 'ctrl', scope: { 'ngmodel': '=' }, template: '<select ng-model="ngmodel" ng-options="v v in ctrl.myvalues"> </select>', link: function(scope, elem, attrs, ngmodelcontroller) { } };
}
html view:
<div selector ng-model="vm.initialvalue"></div>
vm.initialvalue in controller.
i created fiddle that, check here
i hope helps.
Comments
Post a Comment