由于业务的需要,最近angular 的diretive 研究的比较多,有和同事一起共同协作开发scada的项目, 对directive 有了进一步更深的理解。
感觉才开始真正理解了这句话的意思:
In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied
这句话,感觉道出了diretive的原理的精髓。
--------------------------------------------------------------------------------------------------------------------
>
<
@
{{}}
=
&
When we are setting scope: true in directive, Angular js will create a new scope for that directive. That means any changes made to the directive scope will not reflect back in parent controller.
---------------------------------------------------------------------------------------------------------------------
In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.
This is illustrated best with an example:
<div my-customer name="Customer XYZ"></div>
and the directive definition:
angular.module(‘myModule‘, []) .directive(‘myCustomer‘, function() { return { restrict: ‘E‘, scope: { customerName: ‘@name‘ }, controllerAs: ‘vm‘, bindToController: true, controller: [‘$http‘, function($http) { var vm = this; vm.doStuff = function(pane) { console.log(vm.customerName); }; }], link: function(scope, element, attrs) { console.log(scope.customerName); } }; });
scope
In very simple terms, the meaning of the binding symbols is:
someObject: ‘=‘
someString: ‘@‘
{{}}
)
someExpression: ‘&‘
hideDialog()
)
AngularJS directive documentation page, although somewhat spread throughout the page.
>
<!DOCTYPE> <html ng-app="App"> <head> <meta charset="utf-8"/> <script src="./js/angular.min.js"></script> <script> var app = angular.module(‘App‘, []); app.controller(‘appCtrl‘, function($scope){ // $scope.names = {age: 12}; $scope.names = ‘FLY‘; // DB.getAl().then(function (rsp) { // $scope.name=100; // }) $scope.changeNames = function(){ $scope.names = "AAA"; }; $scope.cbFun = function(name){ // alert(‘parent action.‘); alert(name); /** * * * */ }; $scope.doStuff = function () { alert(‘parent scope‘); } }); app.directive(‘myCustomer‘, function(){ return { scope: { fly: ‘@‘ }, restrict: ‘A‘, link: function(scope, element, attr){ console.log(‘attr: ‘, attr); console.log("myCustomer: ", scope); }, controllerAs: ‘vmst‘, bindToController: true, controller: [‘$scope‘, ‘$http‘, function(scope, $http) { var vm = this; console.log(‘this: ‘, this); console.log(‘scope: ‘, scope); vm.doStuff = function(pane) { console.log(vm.customerName); }; vm.name = ‘pxk‘; scope.doStuff = function(){ alert(‘asdfafa‘); } }], // template: ‘<button ng-click="doStuff();">aaaa</button>‘ }; }); </script> </head> <body ng-controller="appCtrl"> <div my-customer="" haha="12ab3" fly="jiayou">myCustomer <button ng-click="doStuff();">aaa</button> </div> <hr/> </body> </html>
原文:https://www.cnblogs.com/oxspirt/p/9242561.html