gpt4 book ai didi

javascript - Angularjs - 我如何访问 Controller 中的指令属性

转载 作者:可可西里 更新时间:2023-11-01 02:53:35 26 4
gpt4 key购买 nike

我是 angularjs 的新手,我被困在 Controller 中访问指令属性。

指令

<rating max-stars="5" url="url.json"></rating>

app.directive('rating', [function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
url: '@'
},

link: function (scope, iElement, iAttrs) {
console.log(iAttrs.url); //works
}

Controller

app.controller('ratingController', ['$scope', '$attrs' , '$http','$routeParams',function  ($scope,$attrs,$http,$routeParams) {


console.log($attrs.url); //shows undefined

}]);

我如何访问 Controller 中的 url 属性?

最佳答案

如果您想将 Controller 与指令相关联,可以使用指令定义对象的 controller属性(将 Controller 指定为函数或指定 Controller 的名称(在这种情况下,它可以在模块中的任何位置注册))。

app.directive('rating', [function () {
return {
restrict: 'E',
scope: {
maxStars: '=',
url: '@'
},
controller: 'ratingController'
};
});

// Meanwhile, in some other file
app.controller('ratingController', function ($scope, $element, $attrs) {
// Access $attrs.url
// Better yet, since you have put those values on the scope,
// access them like this: $scope.url
...
});

当通过 = 使用双向数据绑定(bind)时,相应属性的值不应是文字(因为您不能对文字进行双向数据绑定(bind)),而是指定当前范围内属性名称的字符串。

使用 <rating max-stars="5"...连同 scope: {maxStars: '='...是错误的。
您应该使用 <rating max-stars="5"...scope: {maxStars: '@'...
<rating max-stars="someProp"...scope: {maxStars: '='...而封闭范围有一个名为 someProp 的属性带有数值(例如 $scope.someProp = 5; )。

关于javascript - Angularjs - 我如何访问 Controller 中的指令属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24864956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com