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

Quentin
  • 3,150
  • 4
  • 24
  • 34

3 Answers3

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;
    }
});
Quentin
  • 3,150
  • 4
  • 24
  • 34
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

Sean Doe
  • 277
  • 2
  • 9
  • Ok I'll try it, however will the data-binding still work in this case ? I updated my example with a more detailed example. – Quentin Jan 02 '14 at 11:58
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>...
Stewie
  • 60,366
  • 20
  • 146
  • 113
  • My template structure is a bit more complicated as in the example, so I can't use ng-repeat to select my specific item. – Quentin Jan 02 '14 at 11:51
  • Well, in that case you should update your question to reflect **all** the important side-effects. Otherwise you're disrespecting to the community. – Stewie Jan 02 '14 at 11:54
  • Yes I just did it, didn't think about ng-repeat before your answer, sry – Quentin Jan 02 '14 at 11:57