AngularJs ngApp、ngBind、ngBindHtml、ngNonBindable

ngApp

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

格式:ng-app=”value”

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

使用代码:

  <div ng-app="starer">div>

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

这个指令其实他就是告诉Angular,应用程序的根节点在我这,并且在1.3版本后告诉Angular你该执行的模块的名称是什么。在stater模块下,注意把整个angular应用程序所要依赖的控制器,服务,基础模块等都用一个requires包含在内

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 = 'Hello Wrold';// 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 = 'Hello Wrold';};}());

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>

ng-bind-template

这个指令告诉Angular可以显示多个表达式


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部