angularjs - Angular 绑定(bind)指令的参数到 Controller

标签 angularjs angularjs-directive angularjs-controller

我在绑定(bind)指令的参数(使用隔离范围)以从指令的自定义 Controller 访问它们时遇到问题。

请检查这个 fiddle (打开控制台,查看记录的结果!)http://jsfiddle.net/xj9gqqxn/4/

<div ng-controller="appCtr">
  <div>
    <div custom-directive param="customer.name">
    <span>{{customer.name}}</span>
    <br/>
    <input type="text" ng-model="customer.name"/>
    </div>
  </div>
</div>

当我登录指令的链接函数时,值会相应地被记录,但是当我在 Controller 的构造函数中执行相同操作时,我会看到该值未定义。

如果有人知道如何在指令 Controller 的构造函数中访问指令的参数值,请分享答案或指出我犯错误的地方..对我来说很难过,我没有进一步的线索...

谢谢

最佳答案

你的 Controller 与指令具有相同的作用域,所以这可以正常工作:

app.controller('customController', ['$scope', '$timeout' , function($scope,$timeout) {
    console.log("[customController:new] -  param value is: " + $scope.param);
}])

http://jsfiddle.net/pegla/xj9gqqxn/6/

此外,如果您正在搜索bindToController,因此指令$scope值绑定(bind)到 Controller 而不是$scope,您可以这样做:

bindToController: {
            param: '='
        },

更新了 fiddle : http://jsfiddle.net/pegla/xj9gqqxn/8/

关于angularjs - Angular 绑定(bind)指令的参数到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46533165/

相关文章:

javascript - 使用 angularjs 指令时 Fine Uploader 出现错误

javascript - 分离然后附加 AngularJS 表单更改有效性状态

Angularjs:动态创建的 Controller 加倍

javascript - 使用字节数组中的 PDF.JS 和 AngularJS 渲染 PDF

javascript - 将变量传递给指令 AngularJS

angularjs - 表单有效时启用按钮

javascript - Angular : directives and scope

javascript - AngularJS ui-calendar——带有事件的模型

javascript - 在 AngularJS Controller 之间共享数据?

javascript - RequireJS 和 AngularJS 多 Controller