关于angularJS的新手问题,但是在搜索过的教程中看不到类似的情况。
如何使用相同的指令定义将不同的参数传递给各个div实例?我希望在这里看到,red green blue
但是我blue blue blue
在HTML中看到。我看到控制器在链接之前被调用。
http://jsfiddle.net/gradualstudent/Y2bBy/
<!DOCTYPE html>
<html >
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
var app = angular.module('myApp', []);
app.directive("element", function () {
return {
restrict: "A",
template: '<h1>{{type}}</h1>',
link: function (scope, element, attrs) {
scope.type = attrs.element;
console.log("Setting: "+scope.type);
},
controller: function ($scope) {
console.log("Checking: "+$scope.type);
}
};
})
</script>
</head>
<body ng-app="myApp">
<div element="red">1</div>
<div element="green">2</div>
<div element="blue">3</div>
</body>
</html>
指令的所有实例都使用相同的作用域,并且每次link
调用该函数时,它都会覆盖先前设置的scope.type
。如果创建隔离的作用域,那么它将起作用,因为该指令的每个实例都将获得自己的作用域:
app.directive("element", function () {
return {
restrict: "A",
scope: {},
template: '<h1>{{type}}</h1>',
link: function (scope, element, attrs) {
scope.type = attrs.element;
console.log("Setting: "+scope.type);
},
controller: function ($scope) {
console.log("Checking: "+$scope.type);
}
};
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句