angular.js - A question about AngularJs directives
天蓬老师
天蓬老师 2017-05-15 16:59:28
0
1
473

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.

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
巴扎黑

That’s right, this is often used when writing components in projects

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template