2

I'd like to include a partial template inside my main template, but having a specific scope when I call the partial template.

For example, this is my main template (very simplified, actual template is more complicated, so ng-iterate can't be used here) :

<h1>title, my item1 name is {{item1.name}}</h1>
....
<div ng-view="myPartial.html" scope="item1"></div>
....
<div ng-view="myPartial.html" scope="item2"></div>
...

And myPartial.html is something like

<input ng-model="name" />...

data :

{item1: {name:"test1"}, item2: {name: "test2"}}

expected result :

<1>title, my item1 name is test1</h1>
....
<div><input value="test1" /></div>
....
<div><input value="test2"></div>
...

How would you do this kind of thing using angularjs ?

Should I create a specific directive with myPartial.html as template ? Thanks

3 Answers 3

2

As ng-view can only be found once in the page, I used ng-include and the ng-init to initialize the scope of the specific controller :

<div ng-include="'/myPartial.html'" ng-init="init(items.item1)" ng-controller="YourController"></div>

controller :

this.app.controller("YourController", function YourController($scope) {
    $scope.init = function(item){
        $scope.item = item;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

<div ng-view="myPartial.html" ng-controller="yourController"></div>

and then create yourController as angular controller (or use existing) and assign data to $scope.item1

1 Comment

Ok I'll try it, however will the data-binding still work in this case ? I updated my example with a more detailed example.
0

In case your items are in same format than you will want to use ngInclude. ngView directive is used for different purposes.

Controller:

$scope.items = {item1: {name:"test1"}, item2: {name: "test2"}};

Main view:

<div ng-repeat="item in items" ng-include="'myPartial.html'"></div>

myPartial.html:

<h2>{{item.name}}</h2>...

3 Comments

My template structure is a bit more complicated as in the example, so I can't use ng-repeat to select my specific item.
Well, in that case you should update your question to reflect all the important side-effects. Otherwise you're disrespecting to the community.
Yes I just did it, didn't think about ng-repeat before your answer, sry

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.