Home  >  Article  >  Web Front-end  >  Some valuable details and tips about custom directives in Angularjs

Some valuable details and tips about custom directives in Angularjs

寻∝梦
寻∝梦Original
2018-09-07 16:30:481057browse

This article mainly explains to you what are the valuable details and techniques in angularjscustom instructions. Do you know all of these? If you don’t know, come and take a look at these. Let’s take a look at this article together

1: Commonly used templates for custom instructions

The following is a rough description, not comprehensive. Some details that are not mentioned will be explained in detail later. Details and important related knowledge:

angular.module('yelloxingApp', []).directive('uiDirective', function() {
   return {
        restrict:String,//标明该指令可以在模板中用于元素E、属性A、类C和注释M或组合
         priority:Number,//设置指令执行优先级,在某个DOM上优先级高的会先执行
        terminal:Boolean,
         template:String or Template Function,//就是设置模板,和下面的templateUrl属性二个只可以设置一个,目的一样
        templateUrl:String or Template Function,//除了字符串,这二个属性还可以设置函数
        replace:Boolean,//指令模板是否替换原来的元素
        scope:Boolean or Object,
        controller:String or function(scope, element, attrs) { ... },
        require:String or Array
        //你需要知道link在每个实例都执行一遍,compile全程只会执行一遍
        link: function(scope, element, attrs,ctrl) { ... },
        compile:function(element, attrs) {
            //常用的就是compile的此处写执行一次的代码,或者在link方法里面写和dom有关的操作
        }
    };
});

2: Some attribute descriptions

[scope]

You can set boolean or objects. Let’s talk about boolean first. This comparison Simple:

1. When set to true, it means inheriting the parent scope and is a child scope;

2. When set to false, the parent scope is used directly.

There is another object setting method, which is to set an isolated scope. When using the isolated scope, three methods are provided to interact with places outside the isolation. Here is an example to illustrate one by one:

angular.module('yelloxingApp', []).directive("scopeExample", ['$rootScope', function($rootScope) {
   return {
        restrict: 'A',
        scope: {
            _userDataName: "=userDataName",
            _onSend: "&onSend",
            _fromName: "@fromName"
        },
         template: `
            e1f5a1ee9c6dca37bcd669731a393538
                点击按钮调用父级的方法
            65281c5ac262bf6d81768915a4a77ac0
            4274db3893f1db7d5323331011e4e7a9
            ff6d136ddc5fdfeffaf53ff6ee95f185
                25edfb22a4f469ecb59f1190150159c6fromName={{newfromname}}bed06894275b65c1ab86501b08a632eb
                25edfb22a4f469ecb59f1190150159c6这是从父级获取到的{{_userDataName}}bed06894275b65c1ab86501b08a632eb
            929d1f5ca49e04fdcb27f9465b944689`,
         link: function($scope, element, attrs) {
           //使用@符号可将本地作用域的变量与DOM属性的值进行绑定,即这里通过@得到父类fromName的值
            $scope.newfromname = $scope._fromName;
            $scope._useParentMethod = function() {
                //使用&符号可以在其中调用父类的方法
                $scope._onSend({ "email": { "email": "yelloxing@gmail.com" } });
                console.log($scope._userDataName);
                
            };
        }
    };
}]);

The above is how to write the command. Let’s take a look at what’s in the controller:

$scope.name = "心叶";
$scope.user = "yelloxing";
$scope.sendMail = function(email){
    console.error(email);
}

Finally, don’t forget to use it in html:

fbed9b0f6bf1f7e816b9b0d0c213b15694b3e26ee717c64999d7867364b1b4a3

[require]

Request another controller, and then pass it in as the fourth parameter of the link method. What we need to pay attention to is the method of finding the controller.

The method of finding a controller can be understood like this: use? Indicates that if the required controller is not found in the current command, null will be passed as the fourth parameter to the link function. If the ^ prefix is ​​added, the command will search for the controller specified by the require parameter in the upstream command chain. , they can also be combined, such as require: "?^ngModel". If there is no prefix, the instruction will search in the controller provided by itself. If no controller (or instruction with the specified name) is found, it will throw a mistake. (If you want to learn more, go to the PHP Chinese website AngularJS Development Manual to learn)

[terminal]

Attribute terminal: When true, it indicates that the priority is smaller than the current instruction None of the instructions will be executed, only this instruction will be executed.

3: Data formatting between view and model

Similar to the filter function, sometimes we want the page to display the data after some kind of translation, so as to facilitate agreement. However, for the database, a simple serial number may be more beneficial, so you may need to use the following method in the link to implement this function:

1.ctrl.$formatters.unshift(function(input) {// Data formatting from model to view});

2.ctrl.$parsers.unshift(function(input) {//Data formatting from view to model}).

The above $formatters and $parsers are two queues, view to model and model to view, which will facilitate filtering through the methods defined inside, somewhat similar to pipeline flow, and finally flow to the destination.

Don’t forget to set a statement like require: "?ngModel" to find the controller.

4: View and model data synchronization issues

Sometimes the input data is modified through jquery in the instruction, but angularjs will not know it. At this time, you can choose one of the following Method:

1. Trigger the change of the input box, let Angularjs discover that the data has changed, and then call $setViewValue(value) to synchronize the data: $("input").trigger("change");

2. Directly and manually trigger the behavior of synchronizing value to viewValue and modelValue: ctrl.$setViewValue($scope.info).

Five: Several fragmentary skills

1. Set true or false according to whether the input box is legal: ctrl.$setValidity(errorType, boolean);//errorType represents the error category, you can Customization

2. Set up a specified model value for monitoring, and of course there are methods such as monitoring collections: $scope.$watch(attrs['ngModel'], function(newValue, oldValue) {});

3. Sometimes the newly added string in the instruction needs to be managed by angularjs, you can use the following method to compile it: $compile(newHtml)($scope).

6: Commonly used methods or services

There are two ways to parse a string (it may be an attribute or a method), just look at the example below:

$scope.getInfo=function(){
    console.log('这是执行了函数的表现');
};

var funName="getInfo()";

//执行方法一:
$scope.$eval(funName);
//执行方法二:
$parse(funName)($scope);

Okay Okay, this article ends here (if you want to see more, go to the PHP Chinese website AngularJS User Manual to learn). If you have any questions, you can leave a message below.

The above is the detailed content of Some valuable details and tips about custom directives in Angularjs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn