你的位置:首页 > 软件开发 > Java > AngularJS自定义Directive中link和controller的区别

AngularJS自定义Directive中link和controller的区别

发布时间:2016-01-25 15:00:06
在AngularJS中,自定义Directive过程中,有时用link和controller都能实现相同的功能。那么,两者有什么区别呢?使用link函数的Directive页面大致是:<button id="addItem">Add Item&lt ...

 

在AngularJS中,自定义Directive过程中,有时用link和controller都能实现相同的功能。那么,两者有什么区别呢?使用link函数的Directive页面大致是:<button id="addItem">Add Item</button>Directive方面:

 

(function(){  var withoutController = function(){    var tempalte = '<button id="addItem">Add Item</button><div></div>';        var link = function(scope, element, attrs){          //从scope中的datasource拿到数据源      var items = angular.copy(scope.datasource),      button = angular.element(document.getElementById('addItem'));            button.on('click', addItem);            render();            function addItem(){        var name = 'new customer';                //执行Directive中传入的方法,带参数        scope.$apply(function(){          scope.add()(name);        });                items.push({          name: name        });                render();      }            function render(){        var html = '<ul>';        for(var i=0, len=item.length;i<len;i++){          html += '<li>' + items[i].name + '</li>'        }        html += '</ul>';                element.find('div').html(html);      }    };        reutrn {      restrict: 'EA',      scope: {        datasource: '=',        add: '&'      },      link: link,      template: template    }  };    angular.module('directiveModule')    .directive('withoutController', withoutController);}());
页面大致是:<with-controller datasource="customers" add="addCustomer"></with-controller>Directive方面:

 

(function(){  var withController = function(){    var template = '<button ng-click="addItem()">Add Item</button><ul>' + '<li ng-repeat="item in items">{{::item.name}}</li></ul>',        controller = ['$scope', function($scope){      init();            function init(){        $scope.items = angular.copy($scope.datasource);      }            $scope.addItem = function(){        var name = "customer new";        $scope.add()(name);        $scope.items.push({          name: name        });      }    }];        return {      restrict: 'EA',      scope: {        datasource: '=',        add:'&'      },      controller: controller,      template:template    }  };    angular.module('directiveModule')    .direcitve('withController', withController);}());

原标题:AngularJS自定义Directive中link和controller的区别

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。