【问题标题】:how to pass $scope to angularjs 1.5 component/directive如何将 $scope 传递给 angularjs 1.5 组件/指令
【发布时间】:2016-01-12 23:03:19
【问题描述】:

我正在尝试在 Angular 1.5 中使用新的 .component() 方法。目前我几乎没有找到关于如何使用它的信息。角度文档也没有真正提到它。

我正在尝试将范围或对象从范围传递到 .component 以在组件的模板部分中使用,但我可以传递的唯一两个参数是 $element 和 $attrs。我尝试通过 html 中的属性传递对象,但我得到的只是对象名称的字符串。

我尝试将其设置为以这些方式表示为变量

my-attr="item.myVal"
my-attr="{item.myVal}"
my-attr="{{item.myVal}}"

每次我仍然得到字符串文字而不是变量的值。如何将其设置为变量?

我尝试通过新绑定捕获数据:{},但我的模板:{} 那时没有访问变量的权限。

这是我现在的组件:

export var ItemListAction = {
    controller: 'PanelCtrl as itemCtrl',
    isolate: false,
    template: ($element: any, $attrs: any): any=> {
        var myVal: any = $attrs.myAttr; // returns "item.myVal"
        var listAction: string = compileListAction();
        return listAction;
    }
};

这是我的 HTML 组件

<panel-item-list-action my-attr="item.myVal"></panel-item-list-action>

这是组件的角度模块声明:angular.module('Panel', []).component('panelItemListAction', ItemListAction)

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    模板不需要 $scope。模板函数返回 HTML。你可以像往常一样在控制器中注入 $scope。

    这是 AngularJS 博客对组件的评价:

    module.component

    我们创建了一种更简单的注册组件指令的方式。本质上,组件是一种特殊类型的指令,它们绑定到自定义元素(类似于&lt;my-widget&gt;&lt;/my-widget&gt;),并带有关联的模板和一些绑定。现在,通过使用 AngularJS 1.5 中的 .component() 方法,您可以用很少的代码行创建一个可重用的组件:

    var myApp = angular.module("MyApplication", [])
    myApp.component("my-widget", {
      templateUrl: "my-widget.html",
      controller: "MyWidgetController",
      bindings: {
        title: "="
      }
    });
    

    要了解有关 AngularJS 1.5 组件方法的更多信息,请阅读 Todd Motto 的文章: http://toddmotto.com/exploring-the-angular-1-5-component-method/

    -- http://angularjs.blogspot.com/2015/11/angularjs-15-beta2-and-14-releases.html

    【讨论】:

    • 感谢您的回复,有什么方法可以访问 template:{} 属性中的范围、对象或变量吗?博客没有提到这一点
    • 模板不需要 $scope。模板函数返回 HTML。你可以像往常一样在控制器中注入 $scope。
    • 所以在隔离范围之外,.component() 类似于 ng-include?
    • ng-include 提供对模型变量的动态绑定。当父控制器改变变量的值时,ng-include 销毁旧模板的 DOM 并获取并编译新模板。
    • $scope 不是单例服务。它是由$compile 注入到控制器中的局部变量,并且会根据指令(或组件)的范围层次结构中的位置而有所不同。有关更多信息,请参阅AngularJS $compile API Reference -- controller。另请参阅AngularJS Developer Guide -- scope hierarchies
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 2016-06-15
    • 2015-05-16
    • 2014-06-10
    • 2017-05-31
    • 1970-01-01
    • 2013-01-15
    相关资源
    最近更新 更多