我有一条指令,该指令具有一些基本逻辑,可以隐藏和显示页面上的文本项。此逻辑有一半时间有效,而另一半时间无效。我的指令中包含的代码是:
newco.directive 'heroHeadline', ($routeParams, $interpolate, $rootScope, paramsStateService) ->
restrict: 'E'
templateUrl: '/pages/shared/hero_headline'
scope:
marquee: "="
link: (scope, el, attrs) ->
scope.displayInternationalCopy = false
scope.displayHeadline2 = false
if paramsStateService.customerCategoryId is 'international'
scope.displayInternationalCopy = true
else
classification = $routeParams.classification
classification ?= 'us'
doubleHeadlineClassifications = ["latino", "us"]
scope.displayHeadline2 = if classification in doubleHeadlineClassifications then true
console.log(scope.displayInternationalCopy)
我的模板是:
p.uppercase(ng-if="!displayInternationalCopy")
| Dishworld is now Sling International
h1.invert
span.copy The #1 International
span.copy TV Service in the U.S.
p Sign up today for as low as $25/mo. (and sometimes lower!)
h1#marquee-headline-1.invert ng-if="displayInternationalCopy"
interpolate(value="{{ marquee.headline1 | heroHeadline | perMonth }}" params="basePack")
h2#marquee-headline-2 ng-hide="displayHeadline2 "
interpolate(value="{{ marquee.headline2 | heroHeadline | perMonth }}" params="basePack")
| {{displayHeadline2}}
displayInternationalCopy的console.log显示为false,但是模板的顶部仍在渲染。对于其他情况(当displayInternationalCopy计算为true时)正确显示。我在应用程序的多个位置都使用了这种模式,没有任何问题,这时我很困惑。
另外,该指令正在显示的视图是:
section.jumbotron#international style="background-color: #000" ng-class="{lefty: isDomestic, white: !isDomestic }"
img#hero.hidden-xs height='616' src="{{ marquee.heroImage }}"
.p ng-class="{hero_gradient: !isDomestic}"
.transbox.visible-xs
.copy-international
.container-fluid
.container
hero-headline(marquee="marquee")
a.btn.btn-primary.btn-lg#watch_now(role="button" rel="nofollow" ng-click="signUp($event); toggleHBO(false); " user-flow="")
| {{ classification.cta_button }}
hero-attribution
最佳答案
您正在指令中使用隔离的作用域,该作用域正在创建新的作用域,该作用域通常不是从其父级继承的。那就是说您不能直接在指令内部访问父作用域。您需要使用$parent.
像scope
一样引用父级scope.$parent.displayInternationalCopy
,或者需要在displayInternationalCopy
这样的隔离范围内包含displayInternationalCopy: '='
变量,以便父级的displayInternationalCopy
范围变量在您的内部可用指令范围。