Alw*_*oss 2 html javascript angularjs
我无法在同一个div标签中使用多个指令.以下html不显示模块提供的产品名称
<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
</head>
<body>
<div ng-controller="StoreController as store" ng-repeat="pro in store.products">
<h1>{{pro.name}}</h1>
</div>
<script src='scripts/angular.min.js'></script>
<script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
但是如果我将ng-controller添加到不同的div标签中(见下文),我就能看到产品.这背后的原因是什么?
<!DOCTYPE html>
<html ng-app="gemStore">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css" />
</head>
<body>
<div ng-controller="StoreController as store" >
<div ng-repeat="pro in store.products">
<h1>{{pro.name}}</h1>
</div>
</div>
<script src='scripts/angular.min.js'></script>
<script type="text/javascript" src="scripts/app.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我确实搜索了在单个div标签中使用多个指令,但未能成功找到任何信息.这是AngularJS强加的限制吗?
以下是app.js的内容
(function() {
var app = angular.module('gemStore', []);
app.controller('StoreController', function() {
this.products = gems;
});
var gems = [
{ name: 'Alwin', price: 200, description: "Checking my name" },
{ name: 'Alwin', price: 200, description: "Checking my name" },
{ name: 'Alwin', price: 200, description: "Checking my name" },
];
})();
Run Code Online (Sandbox Code Playgroud)
您可以在同一DOM节点上使用多个指令.您遇到的问题与$compile优先级有关,有什么用ng-repeat.
首先,您必须了解有一个明确的算法,它定义了编译同一DOM节点上的指令的方式.有一个默认priority 参数0.指令是根据此参数编译的,从最高到最低.ng-repeat优先级为1000,ng-controller优先级为500. ng-repeat 首先编译.
其次你需要知道它是如何 ng-repeat工作的.如果您阅读了源,则会看到它使用terminal参数.该参数告诉它应该AngularJS 不低优先级编译任何指令.
因此,在您的代码中,ng-controller永远不会编译("执行").
此外,如果ng-controller没有编译然后ng-repeat没有$scope工作,$digest循环将没有任何事情要做.你会被认为store是未定义的,也是如此store.products,但你错了.如果是这种情况,你会在未定义的对象'store'上看到很多"试图访问属性'产品'",但是你没有,因为代码输入ng-repeat永远不会被执行.