【问题标题】:setting a parent property in a directive in angular with typescript使用打字稿以角度在指令中设置父属性
【发布时间】:2016-05-31 00:42:04
【问题描述】:

鉴于以下html 声明了一个指令。

<div class="form-group"
     data-panda-map-search map="map"
     search-hint="#BuildingName"
     imageUri="{{imageUri}}"
     location-target="#Geolocation">
</div>

和下面的绑定(在html同级:

<div class="col-md-4">
     <img ng-src="{{imageUri}}" alt="" />
</div>

我的目标是在指令中设置imageUri值并让它更新父范围中的图像src。更改图像。

我已经这样声明了范围:

@directive('$http', '$log', 'ISearchService')
export class PandaMapSearch implements ng.IDirective
{
    scopeCopy: any;
    public restrict: string = "A";
    public scope: any =
    {
        map: "=",
        imageUri: "=",
    }
    public link: Function = (scope: any, element: angular.IAugmentedJQuery, attrs: angular.IAttributes) => {
        this.map = scope.map;
        this.scopeCopy = scope;
    }

    public setUri() {
        // attempt to set the value, and change the parent.
        this.scopeCopy.imageUri = 'new url';
    }

稍后在指令中,在一个事件中 - 我设置了this.scopeCopy.imageUri,并得到以下错误:

错误:[$compile:nonassign] 与指令“pandaMapSearch”一起使用的表达式“未定义”是不可赋值的! http://errors.angularjs.org/1.4.9/$compile/nonassign?p0=undefined&p1=pandaMapSearch

更新

我也尝试过this.scopeCopy.$parent.imageUri = ... 这似乎设置了父值,但从未执行摘要。父作用域设置了值,但绑定永远不会更新,因此 src 属性保持不变。

【问题讨论】:

  • 你能创建 jsfiddle 来演示你的问题吗?

标签: angularjs typescript angularjs-directive


【解决方案1】:

我认为您的问题可能与 2 路绑定属性 imageUri="{{imageUri}}" @ imageUri: "=", 有关。您将 imageUri 提到为 2 路绑定属性,因此您应该只绑定该属性,而不是使用插值将其绑定为表达式值。即{{..}}。 2 路绑定属性需要一个可以赋值的属性,因此您提供了一个插值表达式,而不是绑定一个属性。

尝试绑定属性为:

imageUri="imageUri"

或将您的imageUri 绑定更改为@ 绑定(文本绑定),即

public scope: any = {
    map: "=",
    imageUri: "@", //<-- Here
    locationTarget: "@",
    searchHint: "@"
}

【讨论】:

  • 如果我将作用域更改为使用“@”,那么它只是传递一个字符串,那么如何获取更新父作用域值的指令?
  • 如果你想要 2 路绑定,那么你必须使用 =。但是你应该绑定属性而不是我在回答 imageUri="imageUri" 中提到的文本。
  • 是的,我已经这样做了,现在它似乎正确地更新了父范围值。我的问题是它没有触发父母的摘要并实际进行更新。当我设置值时,我需要以某种方式触发父摘要。如果我使用 $('body').scope().apply() 手动触发父级,它会更新页面。
  • 好的。您最初的问题是关于我给出答案的错误。但是,您的手动摘要可能是由于在角度上下文之外发生的属性更新。它需要一个演示副本。
  • 我用这个实现了它:this.$timeout(() =&gt; this.config.Uri = '/api/image/300/500?latitude=${this.marker.getPosition().lat()}&amp;longitude=${this.marker.getPosition().lng()}');
猜你喜欢
  • 1970-01-01
  • 2016-11-08
  • 2013-12-28
  • 2015-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多