Angular学习(2)Directives

来源:互联网 发布:薛冰是怎么死的 知乎 编辑:程序博客网 时间:2024/06/06 23:03

指令继承HTML属性,使用前缀 ng-

ng-app初始化Angular应用,如果里面的html标签要使用的话,必须有一个ng-app包含他们。

ng-init初始化数据,不常用

ng-model,绑定值给html组件(input  select textarea)。

这些在表达式都见过了,基本上例子是下面:
<div ng-app="" ng-init="quantity=1;price=5">

Quantity: <input type="number" ng-model="quantity">
Costs:    <input type="number" ng-model="price">

Total in dollar: {{ quantity * price }}

</div>

有一个新的标签,ng-repeat挺好用的,循环访问数组:

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
  <ul>
    <li ng-repeat="x in names">
      {{ x }}
    </li>
  </ul>
</div>


<div ng-app="" ng-init="names=[
{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]"
>


<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>

然后说了一句:

AngularJS is perfect for database CRUD (Create Read Update Delete) applications.
Just imagine if these objects were records from a database.

为什么呢?


创建新的指令,应该就是自定义指定使用.directive函数。

<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective"function() {
    return {
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>

</body>

函数的第一个参数必须的驼峰命名,比如w3TestDirective,但是我们使用的必须使用-

分开,w3-test-directive。

然后我们可以使用了,有四种方式:

  • Element name
  • Attribute
  • Class
  • Comment
不过我们加限制:

<w3-test-directive></w3-test-directive>  这个被限制了,没法用的


<div w3-test-directive></div>


<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
    return {
        restrict : "A",
        template : "<h1>Made by a directive!</h1>"
    };
});
</script>


<p><strong>Note:</strong> By setting the <strong>restrict</strong> property to "A", only the HTML element with the "w3-test-directive" attribute has invoked the directive.</p>


限制如下:

  • E for Element name
  • A for Attribute
  • C for Class
  • M for Comment

默认是EA,所以不加限制,属性和元素,下面这两个都可以的

<w3-test-directive></w3-test-directive>
<div w3-test-directive></div>

0 0
原创粉丝点击