Angular.js检测双向属性的存在

Angular.js detect presence of bi-directional attribute

本文关键字:属性 存在 js 检测 Angular      更新时间:2023-09-26

这是自我解释的代码,请查看html部分的注释:

HTML:

<div ng-app='myApp'>
<div ng-controller="MCtrl">
  <!-- this should be "test:", OK -->
  <test></test>
  <br>
  <!-- this should be "test: Hello world!", OK -->
  <test custom-target="helloModel"></test>
  <br>
  <!-- this should be "test: Hello !", FAIL! -->
  <test custom-target="emptyModel"></test>
  <br>
</diV>
</div>

JS:

var myApp = angular.module('myApp',[]);
function MCtrl($scope) {
    $scope.helloModel = 'world';
    $scope.emptyModel = '';
}
myApp.directive('test', function() {
   return {
      restrict: 'E',
      scope: {
         customTarget: '='
      },
       template: '<span>test: <b ng-show="customTarget">Hello, {{customTarget}}!</b></span>'
   };
});

http://jsfiddle.net/kMybm/34/

简而言之,我需要属性custom-target是可选的,并且能够检测它何时丢失。

UPD:

目前找到的解决方案:

http://jsfiddle.net/kMybm/35/

也许还有更好的。

第三个示例中的

b标记根本不显示,因为它上有ngShow,当customTarget为空字符串时,它的计算结果为false。