Reputation: 115
I'm new to angularjs and have a bit of trouble trying to do this simple task of updating a scope variable I set in my directive in the calling controller.
So I have a directive:
app.directive('pageShell', function (){
return{
restrict: 'AE',
transclude: true,
replace: true
scope:{
title: '@',
body: '@',
footer: '@'
},
template: '<div class="title-content">{{title}}</div>' +
'<div class="body-content">{{body}}</div>' +
'<div class="footer-content">{{footer}}</div>'
}
});
so in my html:
<page-shell title="Header" body="this is my body" footer="Footer" />
in my controller:
app.c
ontroller("myCtrl", function ($scope) {
// TEST 1 - simple scope change
// switch pages or content so change some values
if(pageIndex === 2) {
$scope.title = "Page 2 title";
$scope.body = "Page 2 body content";
$scope.footer = "Page 2 footer";
}
// TEST 2 - change by using apply
$scope.$apply(function() {
$scope.title = "Page 2 title";
$scope.body = "Page 2 body content";
$scope.footer = "Page 2 footer";
});
});
So I tried in my controller thinking I should have access to my variable in my scope to change it directly but it did not work but did not throw any errors. Tried using $apply
but got the error $apply
is already in progress? Tried changing to 2-way binding in the scope by using =
instead of @
for the title, body, and footer but get a $parse:syntax
error.
Any clue why this simple task wouldn't work? Thanks!
Upvotes: 0
Views: 2380
Reputation: 115
Figured it out: My pageShell directive's scope needs to be:
scope:{
title: '=',
body: '=',
footer: '='
},
The binding needs to be both ways.
the html:
<page-shell title="Header" body="this is my body" footer="Footer" />
and the controller:
Controller("myCtrl", function ($scope) {
// TEST 1 - simple scope change
// switch pages or content so change some values
if(pageIndex === 2) {
$scope.title = "Page 2 title";
$scope.body = "Page 2 body content";
$scope.footer = "Page 2 footer";
}
// TEST 2 - change by using apply
$scope.$apply(function() {
$scope.title = "Page 2 title";
$scope.body = "Page 2 body content";
$scope.footer = "Page 2 footer";
});
});
Upvotes: 2
Reputation: 42669
Your HTML should be something like this
<page-shell title="{{title}}" body="{{body}}" footer="{{footer}}" />
Upvotes: 1