从指令

时间:2016-08-22 20:39:54

标签: angularjs

我尝试从选择下拉列表中选择一个选项时,从自定义指令调用父控制器的功能,但它一直给我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)
        })
    }
}
}])

我试图修改别人的代码,因此很难确切知道发生了什么。

1 个答案:

答案 0 :(得分:5)

你需要将函数从父控制器传递给指令,如下所示(我没有测试就自由处理,因为你没有提供插件,所以我相信你需要调整代码。是函数作为参数传递。如果你不知道如何从父控制器传递变量到指令,你将不会理解这一点,所以首先阅读这个。请注意,我在您的指令中添加了“范围” - 您可以在其中为您的指令定义params,并将其传递给指令的新范围:

您在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)
        })
    }
}
}])

有关说明,请参阅此处的文章: http://weblogs.asp.net/dwahlin/creating-custom-angularjs-directives-part-3-isolate-scope-and-function-parameters

您正在寻找:

  

选项2:存储函数引用并调用它

编辑:我们在这里传递函数有一个很好的例子: AngularJS - pass function to directive

另请注意:

    scope: {
        myFunction: '&',
    }

    scope: {
        myFunction: '&myFunction',
    }

是等价的。一个只是明确地命名它将查找变量的属性,另一个假定属性名称将与范围变量名称相同。