gpt4 book ai didi

javascript - AngularJS 范围属性未定义

转载 作者:行者123 更新时间:2023-12-01 16:55:36 25 4
gpt4 key购买 nike

为什么 $scope.orderBy 未定义?不应该是“测试”吗?

http://jsfiddle.net/XB4QA/4/

var app = angular.module("Foo", []);

app.directive("two", function () {
return {
scope: {
orderBy: '@'
},
restrict: 'E',
transclude: true,
controller: function ($scope, $element, $attrs) {
console.log($scope.orderBy); // is undefined, why?
},
template: '<div></div>',
replace: true
};
});

<div ng-app="Foo">
<two order-by="test">test</two>
</div>

最佳答案

@ 绑定(bind)在指令的范围内进行插值,这种插值稍后发生,在指令链接阶段之后。这意味着虽然指令模板可以使用绑定(bind),但它们在各种指令配置方法中不可用。但是,= 绑定(bind)可立即用于指令,因此如果您希望立即访问,我建议使用此类绑定(bind)。

如果 test 是您想要访问的文字值,请在属性值周围添加单引号,例如:

<two order-by="'test'">

或者如果 test 是一个变量,则只保留 HTML 原样。在任何一种情况下,像这样更改绑定(bind):

scope: {
orderBy: '=' // = instead of @
}

关于javascript - AngularJS 范围属性未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17392337/

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