与其将字符串分配给变量并插入更多 angularjs 方式,不如创建一个指令,以便您获得范围和显示视图所需的一切。
看法
<say-hello-drv></say-hello-drv>
指示
.directive('sayHelloDrv', function () {
return {
restrict: 'E',
template: '<div ng-click="sayHello()">{{text}}</div>',
controller: function ($scope) {
$scope.text = 'Initial hello';
$scope.sayHello = function () {
$scope.text = 'Hello from sayHello()';
}
}
}
}
参考。https://docs.angularjs.org/guide/directive
更新您的用例,顺便说一句,我将用 DDO 的模板属性替换您的指令 HTML 标记:
var myApp = angular.module('myApp',[])
function MyCtrl($scope, $interpolate, $compile) {
console.log($scope)
var template = '<eventPopup ng-click="sayHello()">{{text}}</eventPopup>';
var objList = [{text: "Hello1"}, {text: "Hello2"}];
$scope.sayHello = function () {
alert('hello')
}
for (i = 0; i < objList.length; i++) {
var angularTemplate = $interpolate(template)(objList[i]);
var interpolatedTemple = $('#abc' + i).html($compile(angularTemplate)($scope));
}
}
myApp.controller('MyCtrl', MyCtrl)