javascript - Non-controller ng-click function not working in directive -
this simplification of actual issue.
when button clicked it's parent meant have red background. function not controller function, it's simple view thing. works expected when button not in directive. when used in directive doesn't work. know scope issue, , it's simple solution, i'm knobhead.
i've seen solutions similar issues when click function controller based.
here's plunker: http://plnkr.co/edit/nzpsejy6vh2n4gyethux?p=preview
angular stuff:
var app = angular.module('plunker', []); app.controller('mainctrl', function($scope) { $scope.boxes = [ { id: 1 }, { id: 2 }, { id: 3 } ]; }); app.directive('box', function() { return { templateurl: 'box.html', scope:{ makered: '@' } }; });
view:
<body ng-controller="mainctrl"> <div class="box-wrapper" ng-repeat="box in boxes" ng-class="{redbox: isred}"> <box make-red="isred = !isred" > </box> </div> </body>
directive template:
<div class="box">{{$index + 1}}</div> <button ng-click="{{makered}}">click me</button>
styles:
.box { width: 100px; height: 50px; padding: 10px; border: 2px solid black; text-align: center; font-size: 30px; background-color: white; } .box-wrapper { width: 150px; height: 100px; padding: 20px; border: 2px solid blue; margin-bottom: 20px; } .redbox { background-color: red; }
you're right, it's scope issue.
to use same scope parent, have set scope false in directive, this: scope: false
.
since access parent's scope, can modify it. template box.html becomes :
<div class="box">{{$index + 1}}</div> <button ng-click="isred = !isred">click me</button>
edit
using =
works has suggested.
the directive becames:
scope: { makered: '=' }
the initialisation of directive:
<box make-red="isred"></box>
and directive template:
<div class="box">{{$index + 1}}</div> <button ng-click="makered = !makered">click me</button>
working plunker: http://plnkr.co/edit/ereof4nmz2ipmjrnirvn?p=preview
Comments
Post a Comment