2014-09-12 57 views
0

这里是一个简单的Angular JS示例的HTML和Javascript。在这个例子中,为什么没有链接函数运行并将scope.flag设置为true(boolean)而不是'true'(字符串)?为什么我的AngularJS指令中的链接函数没有运行?

使用Javascript:

angular.module('truthyTypes', []) 
    .directive('myDirective', function(){ 
    return { 
     template: '<div>flag value: {{ flag }}<br/>flag type: {{ flag | typeOf }}</div>', 
     scope: { 
     flag: '@' 
     }, 
     link: function(scope){ 
     scope.flag = scope.flag === 'true'; 
     } 
    } 
    }) 
    .filter('typeOf', function(){ 
    return function(input){ 
     return typeof input; 
    } 
    }) 
; 

HTML:

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Example - example-example78-production</title> 
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.1/angular.min.js"></script> 
    <script src="script.js"></script> 
</head> 
<body ng-app="truthyTypes"> 
    <div my-directive flag="true"></div> 
</body> 
</html> 

直播示例:http://plnkr.co/edit/jqk5529FmdGsxK6Xj8LZ?p=preview

+0

的可能重复[AngularJS - 在指导的链接功能访问隔离范围(http://stackoverflow.com/questions/17111016/angularjs-access-isolated-scope-in​​-directives-link-function) – 2014-09-12 20:56:33

回答

1

您正在使用单向绑定,因此您对指令中的标志变量所做的任何更新都不会传播回控制器。

使用双向绑定(=代替@),改变标志值:

scope: { 
    flag: '=' 
} 

里面的链接功能,那么你可以将标志设置为任何合适的值,例如

scope.flag = true; 
相关问题