[英]Call Parent Controller's Function from Directive
我试图在从选择下拉列表中选择一个选项时从自定义指令调用父控制器的函数,但是它一直给我ng:cpws
错误。
Error: [ng:cpws] http://errors.angularjs.org/1.4.8/ng/cpws
HTML:
<select chosen ng-model="selectedValue.recipientCountry" ng-options="x.Name.toLowerCase() for x in data.RecipientCountries" >
<option value=""></option>
</select>
JS:
uiComponentsModule.directive('chosen', [ function () {
return {
link: function(scope, element, attrs) {
scope.$watch(function (newVal, oldVal) {
scope.$parent.selectRecipientCountry(x)
})
}
}
}])
我正在尝试修改其他人的代码,因此很难确切知道发生了什么。
您需要将函数从父控制器传递给指令,如下所示(我没有进行测试就可以自由处理,因为您没有提供插件,所以我确定您需要调整代码。关键是函数将作为参数传递。如果您不知道如何将变量从父控制器传递给指令,则不会理解,因此请先阅读该内容。 请注意,我在指令中添加了“作用域”,这是您为指令定义参数的地方,这些参数将传递给指令的新范围:
您在html中的指令:
<chosen select-recepient-country = "selectRecipientCountry"></chosen>
您的指令代码:
uiComponentsModule.directive('chosen', [ function () {
return {
scope: {
selectRecipientCountry: '&selectRecipientCountry',
},
link: function(scope, element, attrs) {
scope.$watch(function (newVal, oldVal) {
scope.selectRecipientCountry(x)
})
}
}
}])
有关en的说明,请参见此处的文章: http : //weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters
您正在寻找:
选项2:存储并调用功能参考
编辑:我们这里有一个传递函数的好例子: AngularJS-将函数传递给指令
另请注意:
scope: {
myFunction: '&',
}
和
scope: {
myFunction: '&myFunction',
}
是等效的。 一个只是显式地命名将在其中查找变量的属性,而另一个假定该属性名将与作用域变量名相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.