angularjs - Placing HTML within directive tags -
so far, i've been adding html directive via template/templateurl, wanted able vary template of directive based on page called on. looked online , saw mention of putting html directly in directive tags (in main html file), , i've done that, of code put in html works off root scope rather directive scope, when spoke said should work off directive scope.
is there way bind html in directive tags not imported templates directive scope they're in? or have separate different file , import via templates?
basically, can this:
<setup-itemized> <input type="text" ng-model="si.value"> </setup-itemized>
where si.value
defined , setup in setupitemized
directive rather in root scope?
there many ways achieve that, take example:
http://jsbin.com/sasexum/edit?html,js,console,output
index.html
<div ng-controller="mainctrl ctrl"> <setup-itemized value="ctrl.value"> <input type="text" ng-model="ctrl.value"> </setup-itemized> </div>
main-controller.js:
.controller('mainctrl', function() { vm = this; console.log('loading mainctrl , assign 1 variable value'); vm.value = 1; })
setup-itemized.js:
.directive('setupitemized', function() { return { restrict: 'e', transclude: true, scope: {}, bindtocontroller: { value: '=' }, controller: function($scope) { vm = this; console.log('loading directive controller , assign 10 variable value'); vm.value = 10; $scope.$watch('si.value', function(newval) { console.log('new value variable!'); }); }, controlleras: 'si', template: '<h1>setup itemized</h1>' + '<p>this yuor custom directive transclude!</p>' + '<ng-transclude></ng-transclude>' }; });
as can see need declare "value" variable in parent controller , pass through directive , input. in way, have 2 way binding variable , every change reflected in both controller , directive.
Comments
Post a Comment