我是否应该能够将$ scope中的属性传递给这样的自定义指令?
<div ng-repeat="ratable in ratables">
<div>How much do you like {{ratable.name}}?</div>
<!-- CONFUSED - First element does not work, second element does -->
<rating currentRatingValue="{{ratable.currentvalue}}" maxRatingValue="10"></rating>
</div>
Run Code Online (Sandbox Code Playgroud)
硬连线的"10"很好地传递到指令中,但是当我尝试传递{{ratable.currentvalue}}时,字符串插值似乎永远不会发生.我做错了什么吗?
http://jsfiddle.net/ADukg/2168/
var myApp = angular.module('myApp',[])
.directive("rating", function () {
return {
restrict: "E",
scope: {},
template: "<div class='rating'>Current rating: {{currentratingvalue}} out of {{maxratingvalue}}</div>",
link: function (scope, element, attributes) {
console.log(attributes.currentratingvalue); // Does not work but seems like it should
console.log(attributes.maxratingvalue); // Does work
}
};
});
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.ratables = [
{ name: "sledding", currentvalue: 3, maxvalue: 5 },
{ name: "water skiing", currentvalue: 7, maxvalue: 10 },
{ name: "whitewater rafting", currentvalue: null, maxvalue: 10 }
];
}
<div>
<div ng-controller="MyCtrl">
Hello, {{name}}!
<div ng-repeat="ratable in ratables">
<div>How much do you like {{ratable.name}}?</div>
<!-- CONFUSED - First element does not work, second element does -->
<rating currentRatingValue="{{ratable.currentvalue}}" maxRatingValue="10"></rating>
</div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
Mar*_*cok 10
一些东西:
scope: true$observe 必须用于获取插值属性的值(即使用{{}} s的属性)HTML:
<rating current-rating-value="{{ratable.currentvalue}}" max-rating-value="10"></rating>
Run Code Online (Sandbox Code Playgroud)
指示:
link: function (scope, element, attributes) {
attributes.$observe('currentRatingValue', function(newValue) {
console.log('newValue=',newValue);
scope.currentRatingValue = newValue
})
scope.maxRatingValue = attributes.maxRatingValue;
console.log('mrv=',attributes.maxRatingValue);
}
Run Code Online (Sandbox Code Playgroud)
这是一个使用隔离范围的版本:
.directive("rating", function () {
return {
restrict: "E",
scope: { currentRatingValue: '@',
maxRatingValue: '@' },
template: "<div class='rating'>Current rating: {{currentRatingValue}}"
+ " out of {{maxRatingValue}}</div>",
};
});
Run Code Online (Sandbox Code Playgroud)
如果要在链接函数中查看isolate scope属性的值,则需要使用$observe或$watch因为我们使用了'@'.如果使用'='(对于双向数据绑定),则不需要使用$observe或$watch.