美文网首页javaScript
angular 1x -- 自定义指令(Directive)

angular 1x -- 自定义指令(Directive)

作者: 反者道之动001 | 来源:发表于2017-07-26 11:56 被阅读6次

用ng的Directive函数 构建一个指令(组件)

示例

第一个参数是标签(可以class等方式)名,第二个是回调函数,回调函数返回一个对象。

App.directive("newtag", function(){
    return {
        restrict: "A",
        // 功能相当于vue里面的props (传递数据)
        scope: {
         msg: '='
        }
        replace : true,
        template : "<h1>这是一个组件,这个组件收到了一个name属性的消息:{{data.name}}</h1>"
    }
});

分析

template 就是HTML模板..
可以直接引入<div>...</div>,也可以,引入路径 ./head.html

restrict 是引入方式

对应类型 使用
E element <newtag> </newtag>
A attribute <div newtag></div>
C class <div class="newtag"></div>

**replace ** 对原标签(不一定是标签)的处理
true 的时候,将不会保留痕迹,就跟浏览网页的时候使用了无痕浏览。
scope 数据传递
使用方法

// div 导入 ,这样$scope就多了一个 data属性
<div newtag msg="data"></div>
// js 获取
$scope.data = {
  name: 'xxy'
}

@ 传递字符串
& 传递函数
回调要用的东西。注意他传入的时候,参数有点坑爹,需要实参在对象里面

标签

back = "back(msg, type)"

js

$scope.back = function(msg, type){
  console.log(msg, type)
}

指令里面

 back({
  msg: '回调消息(第一个参数)',
  type: 'params2'
})

transclude 引入模式
--为了code代码的整洁,这个属性在上面Code没展现出来
这个属性为true的话,组件里面的内容会Add到指定标签当中,位置是after。

link
上面的代码没有这个属性。这个也是整个指令的核心。

示例代码

这段code是拷贝gitbooks上的代码

//app.js
var App = angular.module("App", []);

App.directive("people", function(){
    return {
        restrict: "E",
        template : "<p>姓名:{{data.name}}</p><p>性别:{{data.sex}}</p>"
    }
});

App.controller("FirstCtrl", function ($scope) {
    $scope.data = {
        name: "Harry",
        sex : "男"
    };
});

更多

命名

JS 使用驼峰命名。使用的时候用横杆。

视图
// apply刷新视图 不然你会发现多次赋值,后面的视图不更新,等几十秒才更新
 scope.$apply();

....

--END--

相关文章

网友评论

    本文标题:angular 1x -- 自定义指令(Directive)

    本文链接:https://www.haomeiwen.com/subject/abmnkxtx.html