return 'x';不要手动绑定这些内容,而是在模板中执行此操作。
这是一个如何用angular(代码未测试)写这个的例子
js部分:
angular.module('stackoverflow', [])
.controller('questionsCtrl', function($scope, $http) {
$scope.questions = null;
$http.get('stackoverflow.com/questions').then(function(questions) {
$scope.questions = questions;
});
})
.directive('questionsList', {
restrict: 'EA',
templateUrl: 'directives/questionsList.html',
scope: {
questions: '=',
},
controller: function($scope) {
$scope.$watch('questions', function(newValue, oldValue) {
if (newValue !== null) console.log('all questions loaded');
});
}
})
和html:
{{question.title}}
如果您是通过ajax加载html并希望在页面上呈现它(具有角度功能),请考虑使用ng-include指令。否则,您必须使用$compile服务自行编译html:
// example of how to compile html in your controller
// consider thou that $compiling or modifying html from within your controller is considered as bad practice
.controller('someCtrl', function($scope, $element, $compile, $timeout) {
var scope = $scope.$new();
scope.question = {title: 'angular stuff'};
$element.append(
$compile('
);
// will update your html in 2 seconds
$timeout(function() {
scope.question.title = 'javascript stuff';
}, 2000);
});