javascript - 自定义指令上的 Angular 属性困惑

标签 javascript angularjs angularjs-directive

我很困惑为什么这不起作用......

这是我的指令:

app.directive('dateDropDowns', function () {

function link($scope, elem, attr) {

    console.log($scope.startYear);
};

function controller($scope, $attrs, $location) {

};

return {
    link: link,
    scope: {
        startYear: "&",
        endYear: "&",
        date: "=",
        required: "&"
    },
    restrict: "EA",
    templateUrl: "/scripts/templates/datedropdowns.html",
    controller: controller
}
});

这是我的指令 html:

 <div date-drop-downs start-year="startYear" end-year="endYear" required="true" date="testDate"></div>

startYearendYeartestDate 均在上述 html 所在的 Controller 范围内定义。

链接函数中的console.log正在返回:

 function (locals) {
              return parentGet(scope, locals);
            } 

但是,startYear 应该返回 1910,因为这是在调用“date-drop-downs”指令的 Controller 中设置的值。

我尝试过 console.log($scope.$eval($scope.startYear)); 但它返回与上面相同的内容

我尝试过 console.log($scope.$eval(attr.startYear)); 但它返回与上面相同的内容

我尝试过 console.log(attr.startYear); 但只返回文本“startYear”

我不确定如何才能真正获得 startYear 值。

非常感谢任何帮助。

最佳答案

由于您使用的是 & 绑定(bind),如果它们已经不是函数,它们将被包装为函数。这通常用于使用隔离范围调用父级上的方法。

所以你实际上应该这样做:-

$scope.startYear()

要获取 startYear 的值,如果您正在寻找 2 种方式绑定(bind),则应该仅使用 =,如果您只需要它作为文本绑定(bind),则使用 @ 和在指令上将值设置为 start-year="{{startYear}}"

& or &attr - provides a way to execute an expression in the context of the parent scope. If no attr name is specified then the attribute name is assumed to be the same as the local name. Given and widget definition of scope: { localFn:'&myAttr' }, then isolate scope property localFn will point to a function wrapper for the count = count + value expression. Often it's desirable to pass data from the isolated scope via an expression to the parent scope, this can be done by passing a map of local variable names and values into the expression wrapper fn. For example, if the expression is increment(amount) then we can specify the amount value by calling the localFn as localFn({amount: 22}).

为了实现一次性绑定(bind),您可以使用 bindonce或者使用 Angular 1.3beta 你可以使用 one-time binding syntax :-

 .. start-year="{{::startYear}}" ...

 startYear: "@",

<强> Plnkr

关于javascript - 自定义指令上的 Angular 属性困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25496531/

相关文章:

html - float 右 div 间歇性地推出对齐 - angularjs 模板问题?

javascript - 在 AngularJs 中将第一个空输入集中在 html 表单中

javascript - 切换到同一路由时清除现有的 Angular ui 路由器查询参数

angularjs - 如何从angularjs中的模板html调用指令

angularjs - 如果选择了文件,如何启用按钮 Angular JS?

javascript - 获取参数截止值的函数

javascript - $(document).ready() 函数中的代码不适用于 AJAX 回调

javascript - 比较对象并添加不匹配的元素

javascript - 如何通过 Amplify REST 请求传递正文数据?

angularjs - 在 Jasmine 测试中获取自定义指令的 Controller 范围