您的位置:首页 > 移动开发

Angular 学习系列 - - ngApp、ngBind、ngBindHtml、ngNonBindable

2016-02-15 00:00 791 查看
ngApp

使用这个指令自动启动一个AngularJS应用。ngApp指令指定了应用程序的根节点,通常会将ngApp放置在网页的根节点如<body>或<html >标签的。

格式:ng-app=”value”

value:当前应用程序模块的名称。

使用代码:

<div ng-app="Demo"></div>


需要注意的是:1.3版本以前的是可以不设置值的,1.3只后就是必需的了,而且该模块还得被定义,网上很多部分的教程是1.3版本之前的,所以大家在用的时候注意下版本问题。

这个指令其实他就是告诉Angular,应用程序的根节点在我这,并且在1.3版本后告诉Angular你该执行的模块的名称是什么。

ngBind

ngBind告诉Angular去用指定的表达式的值去替换指定元素内的文本内容,并且当表达式的值变化时让文本内容也跟着变化。

格式:ng-bind=”value” class="ng-bind:value;"

value:表达式/值

使用代码:

<div ng-app="Demo" ng-controller="testCtrl as ctrl"> <span ng-bind="ctrl.hello"></span> <span class="ng-bind:ctrl.world"></span><br /> <span ng-bind="ctrl.hi()"></span>
</div>


(function () {
angular.module("Demo", [])
.controller("testCtrl", testCtrl);function testCtrl() {this.hello = "Hello";this.world = "World";this.hi = function () {return "Hi!";
};
};
}());


ngBind相对于{{}}形式绑定的好处就是当你快速刷新或者打开页面那瞬间,不会将绑定代码暴露;相对与{{}}形式来绑定的坏处就是需要载体。所以根据需求来选择用哪个也行,或者ng-cloak避免闪烁。

这个不用过多说明,直接就能看得出这是个绑定数据的指令。

ngBindHtml

创建一个将innerHTML函数所执行的结果绑定到页面指定元素的绑定方式。

格式: ng-bind-html=”value”

value: 将会被html转义并且绑定的字符串。

配合$sce使用:

.hello { width: 300px; height: 300px; background: #ccc; color: red; }


<div ng-app="Demo" ng-controller="testCtrl as ctrl"><div ng-bind-html="ctrl.htmlText"></div>
</div>


(function () {
angular.module("Demo", [])
.controller("testCtrl", ["$sce",testCtrl]);function testCtrl($sce) {      this.htmlText = '<div class="hello">Hello Wrold</div>';// Error: [$sce:unsafe]Attempting to use an unsafe value in a safe context.  this.htmlText = $sce.trustAsHtml(this.htmlText); // ok 能正常输出html了    };
}());


引入angular-ngSanitize.js使用:

<div ng-app="Demo" ng-controller="testCtrl as ctrl">  <div ng-bind-html="ctrl.htmlValue"></div>
</div>


(function () {
angular.module("Demo", ["ngSanitize"])
.controller("testCtrl", [testCtrl]);function testCtrl() {      this.htmlText = '<div class="hello">Hello Wrold</div>';
};
}());


ngNonBindable

这个指令告诉Angular不要去对当前的Dom元素进行编译或者绑定值。当元素的内容需要展示Angular指令和绑定但是又得让Angular忽略他的执行的时候,这个指令就有用了。比如你有个网站,需要展示代码片段的时候。

格式:ng-non-bindable

使用代码:

<span ng-bind="greeting"></span>
<span ng-bind="greeting" ng-non-bindable></span>
<span ng-non-bindable >{{greeting}}</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: