2014-06-28 75 views
0

這工作NG-包括負載對象

<div ng-include="template.html" onload="person='Jane'"></div> 

^這將本地範圍變量person在包括以「簡」(串)

但我想通過一個人的對象被稱爲user{name: 'Jane' }

<div ng-include="template.html" onload="person=user"></div> 

^這個設置本地範圍變量person在包括要被「未定義」

如何將對象作爲局部變量傳遞給ng-include?

+0

可能的重複http://stackoverflow.com/questions/13422966/how-to-specify-model-to-a-nginclude-directive-in-angularjs –

+0

我不認爲這是重複的。糾正我,如果我錯了,'ng-init'沒有爲我解決它,讓我看看我是否可以得到一個jsfiddle去演示 – dylanjha

+0

解決方案是創建一個新的指令,正如我在這個答案中所說:http: //sackoverflow.com/a/36916276/2516399 – smartmouse

回答

1

也許你真正想要的是一個自定義指令:

<div person-directive="{name:'Jane'}"></div> 

JS:

angular.module('myApp',[]) 
.directive('personDirective',function(){ 
    return { 
     restrict: 'A', 
     scope: { 
      person: '=personDirective' 
     }, 
     templateUrl: 'template.html' 
    }; 
}); 

有了這個,你綁定在加載模板傳入的價值person

Working fiddle

+0

是的,指令工程,只是看起來有點矯枉過正,以爲我可以逃脫ng-include。 – dylanjha

+0

矯枉過正?不是真的。 –

1

NG-包括是不是可重複使用的,因爲它沒有提供一種方法來設置局部變量。使用onload是不好的,因爲它拋棄了全局範圍。如果示例稍微複雜一點,它會失敗。

Making a new directive instead of using ng-include是一個更清潔的解決方案。

理想的用法是這樣的:

<div ng-include-template="template.html" ng-include-variables="{ person: 'Jane' }"></div> 
<div ng-include-template="template.html" ng-include-variables="{ person: user }"></div> 

的指令是:

.directive(
    'ngIncludeTemplate' 
() -> 
    { 
     templateUrl: (elem, attrs) -> attrs.ngIncludeTemplate 
     restrict: 'A' 
     scope: { 
     'ngIncludeVariables': '&' 
     } 
     link: (scope, elem, attrs) -> 
     vars = scope.ngIncludeVariables() 
     for key, value of vars 
      scope[key] = value 
    } 
) 

你可以看到,該指令不使用全局範圍。相反,該指令從ng-include-variables讀取對象,並將這些成員添加到它自己的本地作用域中。

這是乾淨的和通用的。

+0

' - >'代表什麼? – smartmouse

+1

這是一個咖啡標記。 '() - > {...}'是'function(){...}' – Tanin