GVKun编程网logo

angularjs – 两个指令(不是嵌套在HTML中)如何相互通信?(angularjs指令的作用)

12

本文将分享angularjs–两个指令(不是嵌套在HTML中)如何相互通信?的详细内容,并且还将对angularjs指令的作用进行详尽解释,此外,我们还将为大家带来关于angularjsng-bind

本文将分享angularjs – 两个指令(不是嵌套在HTML中)如何相互通信?的详细内容,并且还将对angularjs指令的作用进行详尽解释,此外,我们还将为大家带来关于angularjs ng-bind-html 指令 对html标签转译、angularjs – angular ng-bind-html和其中的指令、angularjs – Angular.js如何从一个指令更新范围?、angularjs – Angular2:如何从父组件到子组件进行通信?的相关知识,希望对你有所帮助。

本文目录一览:

angularjs – 两个指令(不是嵌套在HTML中)如何相互通信?(angularjs指令的作用)

angularjs – 两个指令(不是嵌套在HTML中)如何相互通信?(angularjs指令的作用)

我对angularJS很新,我有一个问题(希望它不是那么愚蠢):

我有2个指令(不嵌套):

<div directive1></div>
<div directive2></div>

现在我希望指令与控制器相互通信(Ive在directive1中定义了’controller:’):

myApp
    .directive('directive2',function () {
        return {
            require: "^directive1",link: function (scope,element,attrs,directive1Ctrl) {
                directive1Ctrl.doSomething();
            }
        };
    });

但我总是得到’未找到控制器’例外..(我不确定^因为它只用于通过父母向上搜索).

如果它们没有嵌套,是否不能使用指令2中的directive1中定义的控制器?
我是否必须使用“单独”控制器,它们都需要相互协作?

解决方法

Do i have to use a ‘seperate’ Controller which both require to work with each other?

这很接近.在应用程序的不同部分(两个控制器,两个指令,一个指令和一个控制器等)之间共享数据和功能的标准方法是在服务中提供该数据或功能.然后可以将此服务注入任何需要它的应用程序组件.

在您的情况下,您可以创建一个提供doSomething函数的服务,并将其注入directive1和directive2.

angularjs ng-bind-html 指令 对html标签转译

angularjs ng-bind-html 指令 对html标签转译

文章参考

http://www.tuicool.com/articles/2eIrIz

http://www.runoob.com/angularjs/ng-ng-bind-html.html

在工作中遇到问题:用户在后台添加一篇新闻,在数据库中存储的是HTML代码,从数据库查询出来之后结果把HTML代码显示出来。

解决办法:使用ng-bind-html 指令,能够对HTML代码的标签转译,在浏览器中显示

ng-bind-html 指令会自动过滤掉标签内的样式?

所谓sce即“Strict Contextual Escaping”的缩写。翻译成中文就是“严格的上下文模式”也可以理解为安全绑定吧。

$sce干的事情来看就是将语境中存在的跨站攻击的风险给干掉.

我们返回的内容中包含一系列的html标记,它可以通过使用$sce.trustAsHtml()。该方法将值转换为特权所接受并能安全地使用“ng-bind-html”。所以,我们必须在我们的控制器中引入$sce服务.

代码如下

/** * 公司简介service * */ angular.module("hkApp").factory("companyIntroduceIndexCompanyService",["$http","$sce",function($http,$sce){ return { //获取公司简介 getCompanyIntroduce:function(__scope__){ var url = "/index.PHP/Admin/Page/companyPage.html"; var formData = { id:2 }; $http.post(url,formData) .success(function(response,status,headers,config){ if(response.status == 1){ //__scope__.content = response.data.content; __scope__.content = $sce.trustAsHtml(response.data.content); } }); } } }]);

【1】angular源码分析:angular中入境检察官$sce

【2】野兽的 Angular 学习 - -scesce和sceDelegate

【3】$sce官方手册

angularjs – angular ng-bind-html和其中的指令

angularjs – angular ng-bind-html和其中的指令

Plunker Link

我有一个元素,我想绑定到它的html。

< div ng-bind-html =“details”upper>< / div>

这样可行。现在,随着它我也有一个指令绑定到html:

$ scope.details =’成功! < a href =“#/ details / 12”upper> details< / a>

但指令上面的div和anchor不评估。如何使它工作?

我也面临这个问题,经过几个小时搜索互联网我阅读@ Chandermani的评论,这被证明是解决方案。
你需要用这个模式调用一个’compile’指令:

HTML:

<div compile="details"></div>

JS:

.directive('compile',['$compile',function ($compile) {
    return function(scope,element,attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
}])

你可以看到一个工作fiddle of it here

angularjs – Angular.js如何从一个指令更新范围?

angularjs – Angular.js如何从一个指令更新范围?

如何更新指令范围?
<div ng-controller="MyCtrl">
    <p t></p>
</div>

我的指令:

var myModule = angular.module('myModule',[])
    .directive('t',function () {
        return {
            template: '{{text}}',link: function (scope,element,attrs) {
                scope.text = '1';
                element.click(function() {
                     scope.text = '2';
                });
            }
        };
    })
    .controller('MyCtrl',['$scope',function ($scope) {
    }]);

click指令不更新.

使用 $apply方法:
element.click(function() {
      scope.$apply(function(){
           scope.text = '2';
      });
  });

说明:Databinding in angularjs

angularjs – Angular2:如何从父组件到子组件进行通信?

angularjs – Angular2:如何从父组件到子组件进行通信?

我在标签之间加载了一些div.它如吼叫.

这是我的index.html

<html>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>

<!-- 3. display the application -->

<body>
<my-app>Loading...</my-app>
</body>
</html>

app.module.ts

@NgModule({
imports: [
    browserModule,FormsModule,AppRoutingModule
],declarations: [
    AppComponent,LoginComponent,HomeComponent,NewsFeedComponent,TopBarComponent,SideMenuComponent
],providers : [
    AuthGaurd
],bootstrap: [
    AppComponent
] })
export class AppComponent {}

home.component.ts

@Component({
    selector: 'home',moduleId: module.id,templateUrl: 'home.component.html',providers : [
        LoginService
    ]
})

export class HomeComponent implements OnInit{
isLoggedin : boolean;
constructor (private loginService : LoginService) { }
ngOnInit(): void {
    this.loginService.getLogged().subscribe((isLoggedIn: boolean) => {
        this.isLoggedin = isLoggedIn;
    }); }
}

home.component.html

<side-menu *ngIf='isLoggedin'></side-menu>
<top-bar *ngIf='isLoggedin'></top-bar>
<router-outlet></router-outlet>

auth.gaurd.ts

@Injectable()
export class AuthGaurd implements CanActivate{
    constructor(private router : Router) {
    }
    canActivate(){
        if (localStorage.getItem('isLogin')){
            return true;
        }
        this.router.navigate(['/login'])
        return false;
    }
}

login.service.ts

@Injectable()
export class LoginService {
    private subject: Subject<boolean> = new Subject<boolean>();
    constructor(private router : Router) {
    }
    login(){
        this.setLogged(true);
        localStorage.setItem("isLogin","true");
        this.router.navigate(['/news-Feed']);
    }
    logout(){
        this.setLogged(false);
        localStorage.removeItem("isLogin");
        this.router.navigate(['/login']);
    }
    getLogged(): Observable<boolean> {
        return this.subject.asObservable();
    }
    setLogged(val : boolean): void {
        this.subject.next(val);
    }
}

login.component.ts

@Component({
    selector: 'login',templateUrl: 'login.component.html'
})

export class LoginComponent {
    constructor (private loginService : LoginService) {
    }

    login(){
        this.loginService.login()
    }
}

login.component.html

<input type="number” #mobileNumber />
<input type="password" #password />
<input type="button" (click)="login()">

newsFeed.component.ts

@Component({
    selector: 'newsFeed',templateUrl: 'newsFeed.component.html',})

export class NewsFeedComponent {

}

newsFeed.component.html

一些HTML文本…. !!!!

APP-routing.module.ts

@NgModule({
imports: [
    RouterModule.forRoot([
        {
            path : 'login',component : LoginComponent
        },{
            path : 'news-Feed',component : NewsFeedComponent,canActivate : [AuthGaurd]
        },{
            path : '',redirectTo : '/news-Feed',pathMatch : 'full'
        }
        {
            path: '**',component: LoginComponent
        }
    ])
],exports: [
    RouterModule
]
})
export class AppRoutingModule {}

实际上,当我点击时,它工作正常.就像它的发布完美而不是点击登录按钮它转发到新闻源并显示预期的结果.但是当我从浏览器网址开始时,它不会从home.html加载侧栏和顶栏组件

解决方法

我不确定这是否修复了所有内容,但我认为您希望首先从localstorage读取值以获取最近存储的状态,如果使用BehaviorSubject侦听器,则如果在调用this.subject.emit()之前也调用了最后一个状态订阅者正在订阅.

@Injectable()
export class LoginService {
    //private subject: Subject<boolean> = new Subject<boolean>(false);
    private subject: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(); // <<< changed
    constructor(private router : Router) {
      this.sublect.next(logalStorage.getItem('isLogin')); // <<< added
    }
    login(){
        this.setLogged(true);
        localStorage.setItem("isLogin","true");
        this.router.navigate(['/news-Feed']);
    }
    logout(){
        this.setLogged(false);
        localStorage.removeItem("isLogin");
        this.router.navigate(['/login']);
    }
    getLogged(): Observable<boolean> {
        return this.subject.asObservable();
    }
    setLogged(val : boolean): void {
        this.subject.next(val);
    }
}

今天的关于angularjs – 两个指令(不是嵌套在HTML中)如何相互通信?angularjs指令的作用的分享已经结束,谢谢您的关注,如果想了解更多关于angularjs ng-bind-html 指令 对html标签转译、angularjs – angular ng-bind-html和其中的指令、angularjs – Angular.js如何从一个指令更新范围?、angularjs – Angular2:如何从父组件到子组件进行通信?的相关知识,请在本站进行查询。

本文标签: