0

I have Rails 4.2.4 and Angular 1.4.8.

I am trying define a directive:

index.html:

<div ng-app='myApp' ng-controller='myController'>
    <foo bar='bar'></foo>
</div>

app.js:

angular.module('myApp', ['templates']);

angular.module('myApp', ['templates']).directive('foo', function(){
    return {
        restrict: 'AE',
        scope: {
            bar: '='
        },
        templateUrl: 'bar.html'

    }
});

angular.module('myApp').controller('myController', function($scope, $http){
    $scope.bar = "XMan";
});

bar.html:

<h1> Hi {{ bar }}! </h1>
<ng-include src="'{{bar}}.html'"

XMan.html:

<p>Hello I'm XMan</p>

Here I am expecting my foo directive to render

<h1> Hi X Man! </h1>
<p> Hello I'm XMan </p>

but I am getting

<h1> Hi {{ bar }}! </h1>
<!-- ngInclude: undefined -->

What is wrong with my approach. Please guide me; I am very new to Angular.js.

||||||
  • I think bar.html path will wrong (or), on first case you have made some mistake in control loading. correct : for directive angular.module('myApp', ['templates']).directive('foo', ...... wrong: for controller angular.module('myApp').controller('myController', ...... means you missed up dependency injection of ['templates'] for controller defination – saikumar Jan 12 '16 at 9:01
  • @saikumar When I try angular.module('myApp', ['templates']).controller(... my directive is not loading at all! :( – Sayuj Jan 12 '16 at 9:22
  • try to set ng-app='myApp' to body instead of that div. I think ng-app must be at least parent of element with controller – Manasov Daniel Jan 12 '16 at 10:11
0

I got a solution. We cannot bind ng-include src with scope variable.

Instead I used function call to get the source then it works!

That is I changed

<ng-include src="'{{bar}}.html'"

to

<ng-include src="barUrl()"

and added a controller scope function:

$scope.barUrl = function(){
    return $scope.bar + '.html'
}
||||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.