0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ボタンクリックで取得したng-clickをスコープに反映させる。

Last updated at Posted at 2016-02-14

ソース

ボタンクリックして表示されたaタグ中のng-clickは動作しなかった。scopeの中に入ってるのに。

<!DOCTYPE html>
<html ng-app="app">
<head>
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://code.angularjs.org/1.4.9/angular-resource.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-sanitize.min.js"></script>
</head>
<body ng-controller="getJsonCtrl">
  <button ng-click="getButton()">set button</button>
  <div ng-bind-html=trustClick></div>
  <script type="text/javascript">
  var app = angular.module('app', ['ngResource','ngSanitize'])
  app.controller('getJsonCtrl', ['$scope', '$sce', function($scope,$sce){
    $scope.getButton = function(){
          $scope.click = '<a ng-click=\"show()\">click1</a>'
          $scope.trustClick = $sce.trustAs($sce.HTML,$scope.click)
    };
    $scope.show = function(){
      alert('click!')
    }
  }])
  </script>
</body>

新しく表示されたng-click=show()がscopeに認識されないっぽい。

カスタムディレクティブでcompile,link

ボタンクリックで取得したng-click=show()をcompile,linkでscopeに紐付けると、動作するようにはなった。

カスタムディレクティブ

 <body ng-controller="scopeCtrl">
    <button type="submit" class="btn btn-primary" ng-click="getButton()">set button</button>
    <dir content="trustClick" ng-bind-html="trustClick"></dir>
 </body>

スコープを監視。変化があるともう一回スコープに反映させる。

  app.directive('dir', function($compile, $parse) {
    return {
      restrict: 'E',
      controller:'scopeCtrl',
      link: function(scope, element, attr) {
        scope.$watch(attr.content, function() {
          var getter = $parse(attr.content);
          var clickFunc = getter(scope);
          element.html(clickFunc);
          var linkFn = $compile(element.contents());
          linkFn(scope);
        }, true);
      }
    }
  });

$scope.$applyで出来ないのかなー。また調べよう。もっとスムーズなやり方もあると思うので。
ってかangular2も触ってみたいなと。
demo作りました。
plnkr demo

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?