HTML code
<p ng-controller="MainController">
control:<input type="text" ng-model="testname" />
directive:<xingoo name="testname"></xingoo>
</p>
Angular Code
var myAppModule = angular.module('myApp', []);
myAppModule
.controller('MainController', function($scope){
$scope.testname = 'my name is xingoo';
})
.directive('xingoo', function(){
return{
restrict:'AE',
scope:{
name:'='
},
template:'<input type="text" ng-model="name"/>',
replace:true
};
});
Under these two pieces of code, the control input box is bound to the command input box. Any change in the value on one side will cause changes on the other side. This is my understanding. I don’t know if it’s right or not. I hope God can enlighten me:
1. First, in the controller MainController, we use ng-model to bidirectionally bind the input box and a value testname in the current scope of MainController;
2. In the directive, we specified scope:{name:'='}, so Angular will bind name in the form of a variable, and the value we pass in for name is testname;
3. So, in template:'<input type="text" ng-model="name" />' is actually equivalent to <input type="text" ng-model="textname"/ >;
4. Because the instruction will create a new child scope, and this self-scope can access its parent scope, which is the $scope of the controller MainController, so the input box and our instruction are both Bidirectionally bound to $scope.testname in the current scope.
That’s right, this is often used when writing components in projects