Skip to content

Angular1.x 中的组件封装

javascript
app.directive('childComponent', function () {
    return {
        restrict: 'EAC',
        templateUrl: 'xxx.html',
        scope: {
            attr: '=',
            attr2: '@?',
            event: '&'
        },
        controller: function () {
            // 非必须的属性 判断为空时赋默认值
            $scope.attr2 = $scope.attr2 || 'circle'


            // 子组件中的点击事件
            $scope.handleTabClick = (key, item, index)=> {
                // 调用父组件传入的事件方法时,要使用对象的方式,和模板中的占位变量名对应
                // 下面的 e 会传到父组件中提供的方法的参数 e 上
                // 很逆天
                $scope.handleChange && $scope.handleChange({e: { key, item, index }})
            }
        }
    }
})
js
scope.handleTabChange = e => {
    console.log('顶部菜单切换.e', e)
}
html
<!-- 标签对应 directive 的第一个参数,小驼峰变短横线 -->
<!-- 使用 = 进行双向绑定的可以直接写变量名 -->
<!-- 事件名也得从小驼峰变成短横线 -->
<child-component tabs="attr" handle-change="handleChange(e)"></child-component>

最后更新于: