2014-07-09 131 views
0

我必須錯過一些東西,但我不明白爲什麼這個指令沒有顯示出來,有沒有人可以幫忙?Angular指令不處理此代碼

<body ng-controller="MainCtrl"> 
<p>Test is <b>{{name}}</b> with myValue <b>{{myValue}}</b></p> 
<my-new-directive my-test="{{myValue}}"></my-new-directive> 
</body> 

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
$scope.name = 'World'; 
$scope.myValue = true; 
}); 


app.directive('myNewDirective', function() { 
return { 
restrict: 'E', 
replace: true, 
link: function(scope, element, attrs) { 
    attrs.$observe('myTest', function() { 
    scope.name = attrs.myTest; 
    if (!attrs.myTest) { 
     this.template = '<div>FALSE</div>'; 
    } else { 
     this.template = '<div>TRUE</div>'; 
    } 
    scope.$apply(); 
    }); 
} 
}; 
}); 

​​

回答

1

你不應該從鏈接的函數返回模板。

你可以這樣做:

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope) { 
    $scope.name = 'World'; 
    $scope.myValue = true; 
}); 


app.directive('myNewDirective', function() { 
    return { 
     restrict: 'E', 
     replace: true, 
     transclude: true, 
     template: '<div>{{val}}</div>', 
     link: function(scope, element, attrs) { 
     attrs.$observe('myTest', function() { 
      scope.name = attrs.myTest; 
      if (!angular.fromJson(attrs.myTest)) { 
      scope.val= 'FALSE'; 
      } else { 
      scope.val= 'TRUE'; 
      } 
      scope.$apply(); 
     }); 
     } 
    }; 
    }); 
+0

OKI冷靜,做工精細 –

+0

現在,我試圖做templateUrl類似的東西,但myvalue的將是一個服務調用的結果。任何想法我怎麼能實現呢?需要一個角假人當然肯定:-( –

+0

對於templateUrl你只是更換templateUrl屬性模板屬性:templateUrl:「template.html」 至於服務,一旦你有一個返回值的服務,並更新myValue作用於該範圍,模板會相應地執行。根本不需要更改指令實施。 –

1

我想這減少驗證碼:

<body ng-controller="MainCtrl"> 
    <p>Test is <b>{{name}}</b> with myValue <b>{{myValue}}</b></p> 
    <label><input type="checkbox" ng-model="myValue"> myValue</label> 
    <my-new-directive my-test="myValue"></my-new-directive> 
</body> 

注意,在上面的HTML,my-test直接接收模式,而不是一種表達。另外,我添加了一個包含複選框的演示,以便您可以切換值。

然後,JS是這樣對你似乎什麼需要:

app.directive('myNewDirective', function() { 
    return { 
     restrict: 'E', 
     scope: { 
      name: '=myTest' 
     }, 
     template: '<div>{{ name }}</div>' 
    }; 
}); 

所以基本上,我刪除transclusion,因爲你沒有使用它(如果需要重新添加),並推出了雙向綁定隔離範圍而不是手動添加觀察父範圍模型的值的邏輯。這可以讓您徹底擺脫鏈接功能 - 至少在您需要添加額外功能之前。

+0

好吧,酷將調查這種方式。許多thx –