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

标签 javascript angularjs

我是 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/

相关文章:

javascript - Jquery 文件上传和 Backbone 的上下文

javascript - 为什么日期选择器的值没有改变?

AngularJS Fancybox 弹出窗口

angularjs - angular.module(...).provider(...).info 不是一个函数

javascript - 为什么当通过变量调用 "new"运算符时我的对象属性函数不增加

javascript - 如何更改元素的文本而不影响其子元素?

javascript - 如何在phoneGap应用程序中保护mysql密码?

javascript - Angular 异步函数返回未定义而不是 Promise

javascript - 如何让 Angular 显示正确的验证消息

javascript - angularjs根据其他下拉列表中的选定值过滤下拉列表