angularjs link和contrller的区别

controller先执行,link后执行

  • 指令可以暴露一个API,而link可以通过require与其他的指令控制器交互
  • 所以如果要开放出一个API给其他指令用就写在controller中,否则写在link中
<!doctype html>
<html ng-app="myApp">
<head>
    <script src="angular-1.3.0.js"></script>
</head>
<body>

<div>
    <outer-directive>
    </outer-directive>
</div>

<script>
    var app = angular.module('myApp', [])
    app.directive('outerDirective', function() {
        return {
            scope:{},
            restrict: 'AE',
            template:'<div></div>',
            controller: function($scope) {

                console.log(2222)
            },
            link: function(scope, elem, attrs, controllerInstance) {
                console.log('1111')
            }
        };
    })
</script>

</body>
</html>

输出结果是 222 111

 

下面这个例子主要是基于ngmodel的指令,在实际的项目中,有可能要进行传值,这时候就需要使用到ng-model。如果不使用ng-model那么在一个页面中你所定义的指令就不能复用了

为什么会产生这个因素呢,因为进行数据的交互过程中,directive里面的内容都会想对应的写死掉。所以当引入两个相同指令就会引起冲突发生。

angular.module('myapp',[]).directive('dateselect', function () {
        return {
            restrict: 'E',
            transclude: true,
            scope: {
                bindModel: '=ngModel'
            },
            template: '<div ng-click="change()">改变</div><input ng-model="bindModel"/>',
            link:function(scope){
                scope.change =function () {
                    scope.bindModel="2222"
                }
            }
        }
    }).controller('myctrl',function($scope){
        $scope.birthday="1111";
        $scope.bbb="222";
    })

 

posted @ 2017-03-30 00:55  莺哥  阅读(477)  评论(0编辑  收藏  举报