我有一个页面在我的AngularJS应用程序,其中我想包括相同的html partial,但与不同的变量。如果我这样做在我的主要html:
<div id="div1" ng-include src="partials/toBeIncluded.html onload="var='A'"> <div id="div2" ng-include src="partials/toBeIncluded.html onload="var='B'">
和toBeIncluded.html看起来像
<div>{{var}}</div>
两个div将看起来像
<div id="div1"><div>B</div></div> <div id="div2"><div>B</div></div>
传递给onload的表达式在每次加载新的部分时进行评估。在这种情况下,您要更改var的值两次,因此在两个部分加载时,当前值将为B.
原文链接:https://www.f2er.com/angularjs/146280.html你想传递不同的数据到每个部分/模板(底层html文件是相同的)。要实现这一点,正如Tiago提到的,你可以用不同的控制器。例如,考虑以下
<body ng-controller='MainCtrl'> <div ng-include src='"toBeIncluded.html"' ng-controller='ctrlA' onload="hi()"></div> <div ng-include src='"toBeIncluded.html"' ng-controller='ctrlB' onload="hi()"></div> </body>
在这里,我们有两个部分,每个都有自己的范围由自己的控制器(ctrlA和ctrlB)管理,两个子范围的MainCtrl。函数hi()属于MainCtrl的范围,并且将运行两次。
如果我们有以下控制器
app.controller('MainCtrl',function($scope) { $scope.msg = "Hello from main controller"; $scope.hi= function(){console.log('hi');}; }); app.controller('ctrlA',function($scope) { $scope.v = "Hello from controller A"; }); app.controller('ctrlB',function($scope) { $scope.v = "Hello from controller B"; });
toBeIncluded.html的内容是
<p>value of msg = {{msg}}</p> <p>value of v = {{v}} </p>
生成的html将是沿着以下几行
<p>value of msg = Hello from main controller</p> <p>value of v = Hello from main controller A </p>
和
<p>value of msg = Hello from main controller</p> <p>value of v = Hello from controller B </p>